ES6 – Destructuring, Arrays

Destructuring gives us a way to exact data from a data structure like an object.

Assume we have an array and we want to store the value in different variables. Let’s see how we do in ES5.

This is a inconvenient way of doing this as the list can go on and on. So as to tackle this, ES6 provide us with something known as destructuring.

In ES5, if we have more than one value to be returned, then we would return an object in that case. But in destructuring it is easier. Here is an example for it.

Arrays

From the box example let’s dig into arrays. Here I will be using method querySelectorAll which returns a list, post that I will store the elements in an array and change the color of the boxes to Blue.

This is how we do in ES5

Let’s see how we will do this in ES6

From method will convert the list of boxes into an array.

Breaking in a loop in ES6

We know that we can break in a traditional for loop using continue and break keywords in ES5. However, in case of ES6 it is difficult to break into the loop.

Let’s say if we want to change color/text of the first and third box, keeping the text for 2nd box same. Let’s see how we will do it in ES5 and post that we will have a look on how we will do it in ES6.

The ES6 way

This loop is called for of loop.

About the author

Deepak Sood

Deepak Sood is Lead Consultant in an IT firm holding expertise in Devops and QA Architecture with 8 years of experience.

His expertise is in building highly scalable frameworks. His skills include Java, Configuration Management, Containers, and Kubernetes.

Reach out to him using contact form.

View all posts