Languages
[Edit]
EN

JavaScript - array destructuring with rest parameter

1 points
Created by:
Rubi-Reyna
307

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

In 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 destructuring assignment.

1. Array destructuring

simple destructuring:

// 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

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