Monday, 1 November 2021

Array Destructuring


 

Destructuring

 Destructuring is an ES6/ES2015 feature. Destructuring allows us to break down the complex data structure into a simple data structure. In general, we use this in an array and objects.

Array Destructuring:

Let us consider an array



arr = [88, 96, 76];


To get an individual array value we can assign a value directly to the variable.


const x = arr[0];
const y = arr[1];
const z = arr[2];

The above expression can give the value as in the log if we console the value of x, y, z.


console.log(x,y,z)
// Console log O/P will be
// 88 96 76

the above method is used to assign values / get values from array till ES6/ES2015. 

The Array restructuring is the ES6 method, the above method is done with simple code.


const [x,y,z] = arr;
console.log(x,y,z)
//The result will be same
// 88 96 76

This can be done in a nested array also


const arr = [1, 2, [4, 5]];
const [a, b, [c, d]] = arr;
console.log(a,b,c,d);
// The result in console will be
//1 2 3 4

Similarly, we can extract the required value from the given array. For an instance, we want only the first value and the last value from the given array. We can simply give a hole while we assign variables to the array values. So that unwanted variables can be ignored.


const arr = [1, 2, [3, 4]];
const [a, ,[ , b]];
console.log(a,b);
// The result in console will be
//1 4

These kinds of assignments will help us to retrieve or return specific data with ease using array destructuring.


Thank you!!!

Have a good day!!!

Array Destructuring

  Destructuring  Destructuring is an ES6/ES2015 feature. Destructuring allows us to break down the complex data structure into a simple data...