Array destructuring in JS

Destructing is a way to extract Arrays or objects into a distinct variable.

Destructuring arrays

Arrays are the list of different data types ordered by their index. We can access an item from the array using a certain index by iterating through the loop or manually choosing the index as below. In most cases arrays will have large data and you need to use the loops to get the value. If its small you can use the manual method, but a better way can use with the help of desctructing of array as shown below.

Synatx
[n1, n2] = [1, 2];
Destructuring arrays
const numbers = [1,2,3,4];

// destructuring the array
[n1, n2, n3] = numbers;
console.log(n1);

//literating through the loop
for (const num of numbers) {
  console.log(num);
}

// manually choosing
const num1 = numbers[0];
console.log(num1);
Destructuring Nested arrays
const frameworks = [
  ['react', 'angular'],
  ['django', 'flask']
];

const [jsFrameworks, pyFrameworks] = frameworks;
console.log(jsFrameworks, pyFrameworks);

// ["react", "angular"]
// ["django", "flask"]
Skipping an Item during destructuring

During destructuring, we can skip one elemnent by putting a comma at that index.

const numbers = [1,2,3,4];
[n1, , n3, n4] = numbers;
console.log(n1, n3, n4);
References

Asabeneh
Destructing Mozilla Link
JavaScript Info


Read More