Converting JavaScript to ES6: A blog explaining the benefits of ES6.
Tags: javascript, webdev, programming, es6
Published: 2021-08-09 08:35:34

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s9oe9e3s1htpx01931rz.png)

ES6 let variable:

![Code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ksdsj8wn92eifznw9x0w.png)

ES6 const variable:

![Code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c4n6lsfrkt2f6vb2q5kr.png)

## 2. Arrow Functions

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

![Code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t94fkzzlw3ef5cedjmz5.png)

This is how we rewrite it in ES6 syntax:

![Code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/76epw97ebmolspimvol3.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mjzyzzz4v39hr2jv71mj.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iyncakvx2na8d5l1bi5i.png)

This is how ES6 simplifies it:

![Code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g328u7fxyo1yel6j3v9t.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/945vmq7k10mdf8r3d1iu.png)

Now, let's refactor to template literals!

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5gdrauvx8scn882kmjbe.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/palidfinz4glk485da60.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aw3s53avk1sijs6596zi.png)

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

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aw3s53avk1sijs6596zi.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jry7pwej5711bk1ifrpk.png)

In case of Objects -

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pyc0gmgtd6cg3ahgj7xl.png)

## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xvcjxvbsl1iwkmz4ytue.png)

Now, let's refactor using ES6 default parameter!

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8jp7i6gqds6hgc3y2z3q.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cfaqgex70uafjhtcnjm0.png)

Using Destructuring:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e0c49v4uq6sowbngfxfy.png)

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

Here's how we swap array using traditional syntax.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/65lmhn1xvvu88k7ounuw.png)

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

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/90sx00apypotm2yueuh6.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/odol81qijtb17bsgq0zc.png)

Now let's refactor with destructuring assignment!

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s6y4ee2cnrtpzi7s4ap4.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s6y4ee2cnrtpzi7s4ap4.png)

## 8. Classes

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

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xnan7ni1zud2kgfnfhtt.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ski7an6zbptl0min18bv.png)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dl61fczb88ohs3qdbhnf.png)

## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u9nf190gj37doww5btur.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cqsh2m0g7xudnvs5s4s4.png)

## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fxn0bqwrxwjt92mgm84m.png)

### **Using a Promise**

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

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wx1de3gtbsljxoexe3z6.png)

Example -

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s8khmbri6rsqfav5t2zu.png)

## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tw3x5mfmktan6gtn97j6.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/53n1i95cylvsqezn9pd3.png)

## 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.