Spread Operator and Destructuring arrays and objects in JavaScript

Raunaq Sachdev
Frontend Weekly
Published in
2 min readJan 28, 2018
Source: Google Images

Let us go over two of the most useful(and my favorite!) ES6(ES2015) features: the Spread Operator and Destructuring

All the ES6 code can be transpiled to ES5(or older) using Babel. Babel even provides an online tool to try out the conversion.

Before we start with destructuring, let’s have a short look at the spread operator(…) which was also introduced in ES6. It is used to split an array into a list of comma-separated values which can be used in various places such as function arguments or array matching(which we’ll cover next).

For eg.,

Spread operator with arrays

This operator is very useful in real world scenarios; for eg., finding the max/min number in an array.

Real world use case for the array spread operator

The spread operator can also be used with objects, though it is not a part of the ES6 spec, so you might need to use an extra plugin in your transpiler for it, or be careful with its browser support.

Object spread in JS

The spread operator can be used to shallow copy the properties from one or more objects into another object.

Now that we have an overview of the spread operator, let’s see what destructuring is.

Array Matching:

ES6 version

As we can see on line 3 in the above code, array matching can also be used for swapping values.

The above code is equivalent to:

ES5 version

Another interesting aspect of this operator is that it works over iterables and not just arrays.

Destructuring objects:

ES6

The above syntax is equivalent to:

ES5

As we can see the variable name got the value undefined as there was no match for it. The variables firstName and lastName could be written as it is, and get their name from the property name of the object, and the variable sex gets assigned the property gender from the object.

Using destructuring with function parameters:

This becomes useful when dealing with a function which takes a large number of arguments, or when we do not want to care about the order of the arguments. On the other hand, it makes it necessary for us to fix the names of properties of the object that can be passed.

That’s a basic overview of the spread operator and destructuring in objects and arrays. These are two of my favorite tools from the ES6 spec; they make the code cleaner and probably cooler!

Cheers!

--

--