JavaScript Rest Syntax in Destructuring Tutorial

In this section, we will see what the rest syntax is in destructuring and how to use it in JavaScript.

Note: we’re assuming you’re already familiar with the rest parameter.

What is Rest Syntax in JavaScript Destructuring?

When destructuring an object or an array, we can use the rest syntax as well, and it works the same way.

Note: the rest entry in the pattern must be at the end (just like the rest parameter needed to be at the end of the function parameter list).

Example: using rest syntax in JavaScript Destructuring

const obj = {
  firstName: "John",
  lastName: "Doe",
  email: `[email protected]`
}
const{
  firstName: name = "John",
  ...rest
} = obj; 
console.log(name, rest.lastName, rest.email);

Output:

John Doe [email protected]

Here, the value of the `firstName` property is assigned to the `name` identifier. After that, the engine will create a new object and copy the rest of `property-value` of the target object (the `obj` in this case) into this newly created object and assigns that to the `rest` identifier.

So here the identifier `rest` has two properties named `lastName` and the `email`. Also, they have the same values as those we set in the `obj` object for the two properties.

Example: JavaScript Rest Syntax and Array Destructuring

const list = [1,2,3,4,5,6]
const[
  first,second,
  ...rest
] = list; 
console.log(first, second);
for (let i = 0 ; i<rest.length; i++){
  console.log(rest[i]);
}

Output:

1 2

3

4

5

6

Here, the first and second elements of the `list` are stored in the `first` and `second` identifiers, respectively.

After that, the rest of elements are stored in the `rest` identifier because we applied the rest syntax to this identifier. So the `rest` is basically an array that contains the values `3, 4, 5, 6`.

That’s why we could treat this identifier as an array and loop through it to get all its elements.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies