UI/UX Design

The power of Javascript ES6 – Destructuring and Rest/Spread Operator

In this tutorial I will show you some of the great features from javascript ES6.

Destructuring

This is a convenient way of extracting multiple values from data stored in (possibly nested) objects and Arrays. It can be used in locations that receive data (such as the left-hand side of an assignment).

Let’s say we have a simple array

  
  
let myArray = [1,2,3,4];
  

 
Destructuring would look like:

  
  
let [first, second, third] = myArray;
  

Now the variable first will be 1, second will be 2 and third will be 3

If you want to skip a value, you can do something like:

  
  
let [first, ,third] = myArray;
  

 

Spread

A syntax that allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

Let’s say we have the following function:

  
  
function add(...myNumbers) {
  return myNumbers.reduce((accumulator, currentValue) => accumulator + currentValue);
}
  

 
We can call it this way:

  
  
var numbers = [1, 2, 3];
add(...numbers); // this is a Spread operator
  

This syntax is very useful when you have an unknown (at dev time) number of arguments that you want to pass to a function. You can .push() several values into an array then use them as parameters to a function.

 

Rest

A syntax that looks exactly like spread syntax, but is used for destructuring arrays and objects. In a way, rest syntax is the opposite of spread syntax: spread ‘expands’ an array into its elements, while rest collects multiple elements and ‘condenses’ them into a single element.

This operator takes the form ...variableName which will assign to variableName all the remaining parameters after those that were already assigned.

For example:

  
  
function add(...myNumbers) {  // this is a Rest operator
  return myNumbers.reduce((accumulator, currentValue) => accumulator + currentValue);
}
  

Calling add(1, 2, 3); will return 6. In this example, myNumbers is an Array and is assigned the parameters [1, 2, 3].

Add comment