5 Most useful ES6+ Features

In this post, I am going to share with you Javascript ES6+ features that I find the most useful:

  1. For…of Loop
  2. Arrow Functions
  3. Async and Await
  4. Template literals
  5. Destructing

For…of Loop

Before either we had to write a full for loop or call the forEach function on the array to iterate over its item.

Previously we had to do this

var animals = ['cat', 'dog', 'monkey', 'goat'];
animals.forEach(function(animal) {
    console.log(animal);
});

// OR THIS

for(var i=0; i < animals.length; i++) {
    console.log(animals[i])
}

Now with the new version of JavaScript, we can simply write the For…Of loop

for (let animal of animals) {
    console.log(animals)
}

If we have to iterate over an object’s keys we can use the For…In loop

var address = {
    street: '123 Example Street',
    city: 'TestCity',
    state: 'CoolState'
};

for (let key in address) {
    console.log(address[key]);
}

Arrow Functions

If you have done programming in JavaScript you must be familiar that we have to create a LOT of functions in javascript as it is an asynchronous programming language.

With the new Arrow Functions, it makes the code cleaner and also saves you a few keystrokes.

Consider the following example, previously we had to do this

setTimeout(function() {
    console.log('5 seconds later')
}, 5000)

Now with the ES6+ syntax, it can be compressed into a single line, in a single like arrow function we don’t have to write the return statement, the value of whatever expression preceding the arrow will be returned.

setTimeout(() => console.log('5 seconds later'), 5000)

We can also create multi-line arrow functions that accept multiple arguments

const compute = (arg1, arg2, arg3) => {
    const total = arg1 + arg2 + arg3;
    return total * total;
}

compute(4,5,6)

Async and Await

This is the feature that I use a lot especially when doing server-side programming using Node.JS, but you can also use it on the front-end and it also works in all the major browsers.

With Async and Await keywords, you can write asynchronous code that uses promises appear as if it is synchronous and make the code more readable.

Consider the following example without async await

function doSomething() {
    getData().then((data)=> { //asychronous call
        const dataWithSomething = doSomethingWith(data) //sychronous call
        passDataToAnotherService(dataWithSomething).then((processedData) => { //asychronous call
            doSomeMoreThing(processedData) //sychronous call
        })
    })
}

Now with Async and Await keywords, we can update the code and make the asynchronous functions look like synchronous functions and it results in a much cleaner code, see for yourself:

async function doSomething() {
    const data = await getData();
    const dataWithSomething = await doSomethingWith(data);
    const processedData = await passDataToAnotherService(dataWithSomething);
    doSomeMoreThing(processedData)
}

As you can see with the update the code is much more simplified. To use async-await first you have to create a function with keyword async, then inside the function, you can call asynchronous methods that uses promise and add the await keyword in front of the function call.

Template literals

Template literals is a very useful feature, previously we had to use string concatenation the can quickly get out of hand if we are using multiple values or if want to construct a multi-line string, consider the following example

var bookCount = 100;
var message = 'Your have ' + bookCount + ' books.' 

The code can be simplified with template literals

var books = 100;
var message = `You have ${bookCount} books.`;

To use the template literal we have to enclose the string in ` and then enclose the variable name under ${<variable_name>}

Template literals can also expand to multiple lines

var message = `
    You have ${bookCount} books in your library.
    The most popular title in you collection is: ${popularTitle}.
    Your have favourited ${favBookCount} books.
`

Imagine constructing the above code using string concatenation, it would be an unreadable mess.

Destructuring

Destructuring allows us to extract values from an object and easily assign it to variables.

Considering the following example, here is what we normally do when we want to extract values from an object

var person = {
    name: 'James Bond',
    age: 41,
    occupation: 'plumber'
}

// Without Destructing
const name = person.name;
const age = person.age;
const occupation = person.occupation;

With destructuring you can simplify the code as following:

//With Destructing
const { name, age, occupation } = person;

// And we can normally use the defined variables
console.log(`The name is ${name}`);

and we can use the name, age, and occupation as variables in our code.

That’s it!

These the feature that I find the most useful in ES6+, please share if you found it interesting and let me know in the comments what ES6+ feature you like the best.

 


Posted

in

,

by

Tags:

Comments

Leave a Reply

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