Like any kind of apps, there are difficult issues to solve when we write JavaScript apps.
In this article, we’ll look at some solutions to common JavaScript problems.
Get the Function Name from Within that Function
We can get the function name from within the function by using the name
property.
For instance, we can write:
const foo = () => {
console.log(foo.name);
}
foo();
Then we should see foo
logged.
Load Order of Scripts
If we aren’t loading scripts dynamically or marking them with defer
or async
, then they’re loaded in the order they’re encountered on the page.
This order applies to both inline and external scripts.
Async scripts are loaded in an unpredictable order asynchronously.
Scripts with defer
are load asynchronously, but in the same order that they’re encountered.
This lets us load scripts that depend on each other asynchronously.
Scroll HTML Page to the Given Anchor
We can just set the hash value as the value of location.hash
to scroll to the element with the given ID.
For example, we can write:
const scrollTo = (id) => {
location.hash = `#${id}`;
}
We pass in the ID of the element to scroll to the element with that ID.
Return After Early Resolve or Reject
We need to add a return
after the line that resolves or reject early.
For instance, we can write:
`const add = (a, b) => {` return new Promise((resolve, reject) => {
if (typeof a !== 'number' || typeof b !== 'number') {
reject("a or b isn't a number");
return;
}
resolve(a + b);
});
}
We need to add return
after the reject
call so that the code below it won’t run.
Class vs. Static Method in JavaScript
Class methods are different from static methods in JavaScript.
Class methods have to be called on the instance and can access this
, which is the instance of the class.
Static methods are called directly on the class itself and can’t access this
.
For instance, if we have:
function Foo(name){
this.name = name;
}
Foo.prototype.bar = function(){
console.log(this.name);
}
Then we can call the bar
method if we create a new instance of Foo
:
const foo = new Foo('mary');
foo.bar();
Then 'mary'
should be logged since it’s the value of this.name
property which set when instantiating it.
On the other hand, static methods are defined directly as the property of a constructor:
function Foo(){}
Foo.hello = function() {
console.log('hello');
}
Then we call Foo.hello
directly:
Foo.hello();
and 'hello'
is logged.
With the class syntax, we can put them all in one place:
class Foo {
constructor(name) {
this.name = name;
}
bar() {
console.log(this.name);
}
static hello() {
console.log('hello');
}
}
bar
is a class method and hello
is a static method.
Get a Subarray from an Array
We can get a subarray from an array with the slice
method.
For instance, we can write:
`const arr = [1, 2, 3, 4, 5];
`const arr2 = arr.slice(1, 4);
Then we get [2, 3, 4]
for arr2
. The end index isn’t included.
Preloading Images with JavaScript
To preload images, we can create new img elements with the Image
constructor and set the src
property of it.
For instance, we can write:
const images = [
'http://placekitten.com/200/200',
'http://placekitten.com/201/201',
'http://placekitten.com/202/202',
]
Then we can write:
for (const image of images) {
const img = new Image();
img.src = image;
}
Handling Errors in Promise.all
We can handle errors from Promise.allSettled
by checking if there are any Error
instances from the result.
For instance, we can write:
const getAll = async (`promises`) => {
`const results = await Promise.allSettled(promises);
console.log(result.map(x => s.status));
}`
We get promises
, which is an array of promises.
Then we call Promise.allSettled
to get the results from the promises.
Finally, we get the status of each promise with the status
property.
Conclusion
We can get the name of a function with the name
property.
Loading orders of scripts are in the same order that they’re listed on the HTML.
Class and static methods are different.
We can use slice
to get a subarray of an array.
Promise.allSettled
can get the status of all promises.