how to destructure array in javascript

One way to destructure an array in Javascript is by using the destructuring syntax with square brackets. Here is an example:

index.tsx
const myArr = [1, 2, 3];
const [a, b, c] = myArr;

console.log(a); // output: 1
console.log(b); // output: 2
console.log(c); // output: 3
138 chars
7 lines

We can also use the spread operator (...) to capture the rest of the elements in the array:

index.tsx
const myArr = [1, 2, 3, 4, 5];
const [a, b, ...rest] = myArr;

console.log(a); // output: 1
console.log(b); // output: 2
console.log(rest); // output: [3, 4, 5]
161 chars
7 lines

This can also be done in function parameters:

index.tsx
function myFunc([a, b, ...rest]) {
  console.log(a); // output: 1
  console.log(b); // output: 2
  console.log(rest); // output: [3, 4, 5]
}

myFunc([1, 2, 3, 4, 5]);
167 chars
8 lines

gistlibby LogSnag