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.
Skip Over an Element in .map()
We can skip over an element in map
by using filter
to filter out the entries we don’t want first.
For instance, we can write:
const sources = images.filter((img) => {
return img.src.split('.').pop() !== "json"
})
.map(img => img.src);
Now we only map the items that doesn’t end with 'json'
.
Interpolate Variables in Strings in JavaScript
We can use template strings to interpolate variables in strings.
For example, we can write:
const a = 5;
const b = 1;
console.log(`sum is ${a + b}.`);
We interpolated the result of a + b
into our string in the last line.
The Optimum Way to Compare Strings in JavaScript?
To compare 2 strings in JavaScript, we can use the localeCompare
method.
For instance, we can write:
strA.localeCompare(strB)
This lets us compare strings in a locale-sensitive manner.
Wait Until All Promises Complete Even if Some Rejected
To wait for promises to complete, we can use the Promise.allSettled
method.
It’ll complete even though some may be rejected.
For instance, we can write:
Promise.allSettled([promise1, promise2])
.then(([result1, result2]) => {
// ...
});
We pass in an array of promises.
Then we call then
and we get all the results in an array.
Each result object has the status
and reason
or value
properties.
status
is the promise’s status. If it’s fulfilled, status
will be 'fulfilled'
. Otherwise, it’ll be 'rejected'
.
value
is the resolved value.
reason
is the error for rejection.
For loop for HTMLCollection elements
To loop through a HTMLCollection
object, we can use the for-of loop to do it.
For instance, we can write:
const els = document.getElementsByClassName("foo");
for (const item of els) {
console.log(item.id);
}
We get all the items with class name foo
.
Then we use the for-of loop to loop through them.
To convert it to an array, we can use the Array.from
or the spread operator:
const arr = Array.from(document.getElementsByClassName("foo"));
or:
const arr = [...document.getElementsByClassName("foo")];
Now we can use array methods on it.
Get the Number of Days Between Two Date Strings
We can get the number of days between 2 days by parsing the dates and then get their difference.
Assuming that our dates are in MM/DD/YYYY format, we can write:
const parseDate = (str) => {
const [month, day, year] = str.split('/');
return new Date(year, month-1, day);
}
const dateDiff = (first, second) => {
return Math.round((second - first)/(1000 * 60 * 60 * 24));
}
We split the str
date string.
Then we pass the split items into the Date
constructor as arguments.
year
has the year, month
has the month, but we’ve to subtract it by 1 since JavaScript constructor assumes that 0 is January, 1 is February, etc.
day
is the day of the month.
In dateDiff
, we get the difference by subtraction the second
by the first
.
They’re both Date
instances.
Then we divide by the number of milliseconds in a day.
Then we can write:
const diff = dateDiff(parseDate('2/1/2000'), parseDate('3/2/2000'));
to use it.
Use a Variable for a Key in a JavaScript Object Literal
We can use a variable for a key in JavaScript object literals.
For instance, we can write:
const prop = "foo",
const obj = { [prop]: 10 };
We just pass in prop
into the brackets, then the key would be foo
.
Get the Rendered Height of an Element
We can use the clientHeight
, offsetHeight
, and scrollHeight
to get the rendered height of an element.
For example, we can write:
const height = document.querySelector('div').clientHeight;
or:
const height = document.querySelector('div').offsetHeight;
or:
const height = document.querySelector('div').scrollHeight;
clientHeight
includes the height and vertical padding.
offsetHeight
includes the height, vertical padding, and vertical borders.
scrollHeight
includes the height of the contained document, vertical padding, and vertical borders.
Conclusion
We can use filter
with map
to map selected entries of arrays.
There are a few ways to get the height of elements.
We can get the number of days between 2 dates by create date objects then subtracting them and dividing them by the number of milliseconds in a day.
Promise.allSettled
lets us wait for all promises to finish regardless of their status.