Categories
JavaScript Best Practices

Ways to Write Better JavaScript — Use Modern JavaScript Features

Spread the love

The way we write JavaScript can always be improved. As the language evolves and more convenient features are added, we can also improve by using new features that are useful.

In this article, we’ll look at some modern JavaScript features that we should use to make our lives easier.

**async** and**await**

async and await lets us chain promises in a shorter way. For instance, we can write:

(async () => {
  const res = await fetch('https://api.agify.io/?name=michael');
  const data = await res.json();
  console.log(data);
})();

instead of:

fetch('https://api.agify.io/?name=michael')
  .then(res => res.json())
  .then(data => console.log(data))

With async and await , we eliminated the need to call then and return promises in callbacks.

This is much better than nesting anything. This makes our code easier to read and write.

To catch errors with async and await , we can use try...catch with async function as follows:

(async () => {
  try {
    const res = await fetch('https://api.agify.io/?name=michael');
    const data = await res.json();
    console.log(data);
  } catch (err) {
    console.log(err);
  }
})();

We just use the existing try...catch syntax to catch errors.

With the old catch method, it’s a bit longer:

fetch('https://api.agify.io/?name=michael')
  .then(res => res.json())
  .then(data => console.log(data))
  .catch(err => console.log(err))

Then catch will catch the error and display the content.

The 2 are equivalent. It’s just that async and await are shorter than the old then and catch methods.

**let** and**const**

let and const are must-use when we need to declare variables or constants respectively.

They completely replace var and does a much better job than var for declaring variables.

let and const are both block-scoped, and the variables and constants declared with them can only be used after they’re declared.

On the other hand, var is function scoped and the variable declaration itself is hoisted to the top of the code without the value.

var causes so much confusion that they all should be replaced with let and const .

const should also be used so that values declared with them can’t be reassigned. They also must have an initial value assigned to them immediately when it’s declared.

Probably most entities should be declared with const since most of them shouldn’t be reassigned to a different value.

Note that values declared with const are still mutable, they just can’t be reassigned.

For instance, if const is used to declare an array, we can call push to add more items to the array.

Object properties can also be assigned to different values.

Arrow Functions

Arrow functions are another must-use modern JavaScript feature. It’s shorter and also we don’t have to worry about the value of this inside an arrow function.

Legacy constructs like the arguments object also can’t be used within an arrow function, which is good.

We can use it to declare anonymous functions for callback or we can assign them to a variable or constant.

For instance, we can write:

fetch('https://api.agify.io/?name=michael')
  .then(res => res.json())
  .then(data => console.log(data))

Then we have arrow functions in the then callback which returns promises in the first then callback and calls console.log in the 2nd then callback.

As we can see, we returned something without using the return keyword in single-line arrow functions.

This is also much shorter than using the traditional functions since we don’t have to type out the function keyword.

However, if we have a multiline arrow function, then we have to use the return keyword and parentheses to return a value.

For instance, if we have a long function, we write something like:

const sum = (...nums) => {
  return nums.reduce((a, b) => a + b, 0)
}

Spread Operator

The spread operator lets us copy and combine objects in ways that are hard to do without it.

For instance, with objects, we can write:

const obj1 = {
  a: 1
};
const obj2 = {
  b: 2
};
const merged = {
  ...obj1,
  ...obj2
}

The merged is {a: 1, b: 2} since we spread the entries from obj1 and obj2 into a new object.

The only other way is to use the Object.assign method, which we use as follows:

const obj1 = {
  a: 1
};
const obj2 = {
  b: 2
};
const merged = Object.assign({}, obj1, obj2);

We can also use it to merge arrays into one. We can use it as follows:

const arr1 = [1, 2];
const arr2 = [3, 4];
const merged = [...arr1, ...arr2];

The code above will spread arr1 and arr2 ‘s entries into the merged array.

And so merged is [1, 2, 3, 4] .

Conclusion

Using modern JavaScript features is a must for any JavaScript app to keep the code clean and short.

Some useful features include the spread operator, arrow functions, let and const , and async and await .

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 *