EN
JavaScript - array destructuring with rest parameter
1
points
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.