Categories
JavaScript Tips

Useful JavaScript Tips — Objects, Undefined, and Month Names

Spread the love

Like any kind of apps, JavaScript apps also have to be written well.

Otherwise, we run into all kinds of issues later on.

In this article, we’ll look at some tips we should follow to write JavaScript code faster and better.

Nullish Coalescing

The bullish coalescing operator is better for returning default values than the || operator.

|| returns the right expression if the left expression is falsy.

?? only returns the right expression if the left expression is null or undefined .

Therefore, instead of writing:

const favoriteColor = color || 'green';

We write:

const favoriteColor = color ?? 'green';

It’s going to be available in ES2020, which should be released any minute.

Replace Whitespace Inside a String

We can replace whitespace inside a string with the replace method and some simple regex.

To make the replacement, we write:

const str = 'hello world ';
const noSpace = str.replace(/s/g, '')

Then we get that str ‘s whitespaces are removed since s stands for whitespaces.

The new string with the spaces removed is returned, then we can assign it to something else.

Optional Chaining

We can use the optional chaining operator to allow us to navigate nested object properties safely.

For instance, instead of writing:

const color = dog && dog.color && dog.color.name;

to check if each nested property is defined.

We can just write:

const color = dog?.color?.name

The ?. will check if the nested property is defined automatically return undefined automatically if any nested property in the chain isn’t defined.

It’s available in ES2020, and browser support is being added for it.

Dynamic Imports

We don’t have to import modules statically.

There’s the import function to let us import modules dynamically.

We can write:

const module = await import('module');

to import a module with the import function, which returns a promise.

This is why we have the await keyword before the calling import .

With support for top-level await coming, we can have this line on its own.

To do a default import, we can write:

const module = (await import('module')).default()

Calling the default method will resolve to the default export.

Iterate Over Object Properties

We can iterate over object properties in various ways.

We can use the for-in loop to loop over object properties.

For instance, we can write:

for (const key in obj) {
  console.log(key)
}

This will loop over both non-inherited and inherited properties of obj .

The Object.entries method returns the key-value pairs of an object as an array.

It returns the non-inherited properties.

For instance, we can write:

Object.entries(items).forEach(item => {
  console.log(item)
})

or:

for (const item of Object.entries(items)) {
  console.log(item)
}

Both of them will loop through the key-value pairs.

Wait for Multiple Promises to Resolve

If we have 2 or more unrelated promises that we want to wait to resolve, then we use Promise.all to do that.

For instance, we can write:

const data = await Promise.all([promise1, promise2])

Assuming that promise1 and promise2 aren’t dependent on each other, we can get the resolved data of each in an array.

data has an array of resolved values of all the promises.

Get the Month Name of a JavaScript Date

We can get the month name of a JavaScript date by writing:

const date = new Date(2020, 0, 1);
const monthName = date.toLocaleString('default', { month: 'long' });

The toLocaleString method returns the month name for us.

Therefore, monthName is 'January' .

'long' means we return the long name.

Get the Last Element of an Array

We can get the last element of an array with the index arr.length — 1 where arr is an array.

For instance, we can write:

const arr = ['red', 'blue', 'green'];
const last = arr[arr.length - 1];

Then last would be 'green' .

Conclusion

We can use the nullish coalescing operator to return the default value.

The optional chaining operator can be used for safe navigation.

Also, we can get month names, object entries, and the last item of the array easily.

We can do dynamic imports with the import function. It imports modules asynchronously.

If we have multiple independent promises, we should use Promise.all to run them in parallel.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *