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.
Simple destructuring example:
xxxxxxxxxx
1
let [a, b] = [1, 2];
2
3
console.log(a); // 1
4
console.log(b); // 2
Using rest operator:
xxxxxxxxxx
1
let [a, b, rest] = [1, 2, 3, 4, 5];
2
3
console.log(a); // 1
4
console.log(b); // 2
5
console.log(rest) // 3, 4, 5
Using trailing commas:
xxxxxxxxxx
1
let [,,,d,e] = [1, 2, 3, 4, 5];
2
3
console.log(d) // 4
4
console.log(e) // 5
Trailing commas & rest operator:
xxxxxxxxxx
1
let [,,b,rest] = [1, 2, 3, 4, 5];
2
3
console.log(b) // 3
4
console.log(rest) // 4, 5
Simple destructuring:
xxxxxxxxxx
1
let { a, b } = { a: 1, b: 2 };
2
console.log(a); // 1
3
console.log(b); // 2
Using rest operator:
xxxxxxxxxx
1
let { a, b, rest } = { a: 1, b: 2, c: 3, d: 4 };
2
3
console.log(a); // 1
4
console.log(b); // 2
5
console.log(JSON.stringify(rest)); // {c: 3, d: 4}
Note:
JSON specification doesn't allow trailing commas.