DEV Community

Cover image for Converting JavaScript to ES6: A blog explaining the benefits of ES6.
Husain Bhagat
Husain Bhagat

Posted on

Converting JavaScript to ES6: A blog explaining the benefits of ES6.

If you're still writing your code in ES5, it's about time you got "ES6". ES6 is a new generation of Javascript that will make writing cleaner and powerful code easier than ever before. This blog post should set you on your path to converting ES5 to ES6.

So what is ES6?

ECMAScript 6 (ES6) was the second major revision to Javascript in 2015, which simplifies the code and enables us to write less and do more. It has a lot of new features and new syntaxes to make your code looks more modern, more structured and more readable.

1. Variable Creation using let and const

let: It is a mutable variable, which means we can reassign its value. let can be declared without being initialized. It is much similar to var but you cannot redeclare the same let variable again in the same scope unlike in var. This is very useful during programming as it avoids mistakes.

const: It is an immutable variable except when it is used in objects, which means we cannot reassign its value to const variables. const must be initialized during declaration.

let is the same as const in that both are blocked-scope. It means that the variable is only available within its scope.

Traditional var variable:

Code

ES6 let variable:

Code

ES6 const variable:

Code

2. Arrow Functions

Let's start by showing you how we write the function in traditional syntax:

Code

This is how we rewrite it in ES6 syntax:

Code

It's awesome since the arrow function makes your code looks clean, more structured and more readable.

When the body inside arrow function has more than one line, we need to wrap it inside {} like this:

Code

Arrow functions are frequently used as callbacks. You will find them a lot when you're working with map(), filter() and reduce().

This is how we traditionally write a map function:

Code

This is how ES6 simplifies it:

Code

Although the addition of Arrow Functions is powerful, there are limitations that we need to understand in order to avoid errors that will be difficult to track down, such as when using the this keyword inside an arrow function.

3. Template Literals

Template literals are a new addition in ES6 just like string interpolation, but more powerful because you can use expressions inside them.

Let's take a look at code example below.

This is how we create greetings function that will greet the given name in traditional syntax.

Alt Text

Now, let's refactor to template literals!

Alt Text

Here, we can more easily see the structure of the data in our code. We don't need the + sign anymore and we can use ${} to call variables.

4. Rest Parameters and Spread Syntax

Previously, before we had rest parameter, we had to code like this to convert arguments to array. However, it only supports limited number of arguments and you need to be sure how many items are there.

Alt Text

But with ES6, it introduced the REST Parameter. It accepts unlimited arguments and returns it as array. You can use rest parameter by adding three dots .... . When you use rest paramater as argument inside a function, it must be at the end.

Alt Text

Because it turns our parameters into an array, we can combine it with map() just like the example below.

Alt Text

Next we have spread syntax ..., which looks exactly the same as rest parameter. However, spread syntax does quite the opposite of rest parameter. With spread syntax we can get list of arguments from array or Key-Value pairs in the case of Objects.

It can be used for creating the reference elements.

Alt Text

In case of Objects -

Alt Text

5. Default Parameters

In ES6, we can give default value to function's parameters.

With the old syntax, this is how we create default value to a parameter.

Alt Text

Now, let's refactor using ES6 default parameter!

Alt Text

It's so simple and easy to understand. This also helps you to handle error in advance when you forget to assign the parameter.

6. Destructuring Assignment

Destructuring allows us to Unpack arrays or Objects into a bunch of variables which makes working with arrays and objects more convenient.

Array

The traditional way:

Alt Text

Using Destructuring:

Alt Text

We can also use destructuring assignment to swap between two values in array.

Here's how we swap array using traditional syntax.

Alt Text

And now, let's refactor the code using destructuring assignment!

Alt Text

We have less code and it's easier to understand, isn't it awesome?

Object

We can also use destructuring assignment with object. Take a look at the example below.

Here's how we do it with traditional syntax to get the object's value.

Alt Text

Now let's refactor with destructuring assignment!

Alt Text

There's a lot more you can do with destructuring assignment as it is really useful and practical, especially when you are working with modern Javascript.

7. Array Functions: find() and findIndex()

find() is used to search for element in the array that matches some condition. it returns the first element that matches the condition.

findIndex() returns the index of the element.

Alt Text

8. Classes

Classes are a template for creating objects. They encapsulate data with code to work on that data.

Alt Text

The body of a class is executed in strict mode, i.e., code written here is subject to stricter syntax for increased performance.

Strict mode makes several changes to normal JavaScript semantics:

  • Eliminates some JavaScript silent errors by changing them to throw errors.
  • Fixes mistakes that make it difficult for JavaScript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that's not strict mode.
  • Prohibits some syntax likely to be defined in future versions of ECMAScript

Example -

Alt Text

Alt Text

9. Import and Export

Using import and export in your JavaScript application makes it more powerful. They allow you to create separate and reusable components.

It is simple! export allows you to export a module to be used in another JavaScript component. We use import to import that module to use it in our component.

Export: You can export a variable using the export keyword in front of that variable declaration. You can also export a function and a class by doing the same.

Alt Text

Import: You can import a variable using import keyword. You can specify one of all the members that you want to import from a JavaScript file.

Alt Text

10. Promises

A promise is used to handle the asynchronous result of an operation. JavaScript is designed to not wait for an asynchronous block of code to completely execute before other synchronous parts of the code can run. For instance, when making API requests to servers, we have no idea if these servers are offline or online, or how long it takes to process the server request.

With Promises, we can defer execution of a code block until an async request is completed. This way, other operations can keep running without interruption.

Promises have Three States:

  • Pending: This is the initial state of the Promise before an operation begins
  • Fulfilled: This means the specified operation was completed
  • Rejected: The operation did not complete; an error value is usually thrown

Creating a Promise

The Promise object is created using the new keyword and contains the promise; this is an executor function which has a resolve and a reject callback. As the names imply, each of these callbacks returns a value with the reject callback returning an error object.

Alt Text

Using a Promise

Using a promise that has been created is straightforward; we use .then() and .catch() to our Promise like:

Alt Text

Example -

Alt Text

11. Async and Await

An async function is a modification to the syntax used in writing promises. An async function returns a promise -- if the function returns a value, the promise will be resolved with the value, but if the async function throws an error, the promise is rejected with that value.

Alt Text

Await is only used with an async function. The await keyword is used in anasync function to ensure that all promises returned in the async function are synchronized, ie. they wait for each other. Await eliminates the use of callbacks in .then() and .catch(). In using async and await, async is prepended when returning a promise, await is prepended when calling a promise. try and catch are also used to get the rejection value of an async function.

Alt Text

Conclusion

Understanding the concepts of Callbacks, Promises, and async/await can be tricky sometimes, it was for me, but till now we have seen how they will work when carrying out asynchronous operations and other ES6 features in JavaScript.

These techniques will come in handy a lot when making API requests and event handling.

I hope you guys found this article useful, and I hope I was able to introduce you to some of the ES6 features.

Top comments (0)