Languages
[Edit]
EN

JavaScript - array destructuring with rest parameter

1 points
Created by:
Rubi-Reyna
677

In this article, we would like to show you how to destructure arrays with the rest parameter in JavaScript.

In the below examples we use:

  • destructuring assignment syntax that allows us to extract data from arrays or objects into separate variables,
  • trailing commas (or final commas) - which are also allowed on the left-hand side while using the destructuring assignment.

1. Array destructuring

Simple destructuring example:

// ONLINE-RUNNER:browser;

let [a, b] = [1, 2];

console.log(a);  // 1
console.log(b);  // 2

Using rest operator: 

// ONLINE-RUNNER:browser;

let [a, b, ...rest] = [1, 2, 3, 4, 5];

console.log(a);    // 1
console.log(b);    // 2
console.log(rest)  // 3, 4, 5

Using trailing commas:

// ONLINE-RUNNER:browser;

let [,,,d,e] = [1, 2, 3, 4, 5];

console.log(d)  // 4
console.log(e)  // 5

Trailing commas & rest operator:

// ONLINE-RUNNER:browser;

let [,,b,...rest] = [1, 2, 3, 4, 5];

console.log(b)     // 3
console.log(rest)  // 4, 5

2. Object destructuring

Simple destructuring:

// ONLINE-RUNNER:browser;

let { a, b } = { a: 1, b: 2 };
console.log(a);  // 1
console.log(b);  // 2

Using rest operator: 

// ONLINE-RUNNER:browser;

let { a, b, ...rest } = { a: 1, b: 2, c: 3, d: 4 };

console.log(a);  // 1
console.log(b);  // 2
console.log(JSON.stringify(rest));  // {c: 3, d: 4}

 

Note:

JSON specification doesn't allow trailing commas.

References

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join