javascript

Array Destructuring in Javascript

Array Destructuring in Javascript

 

What is Destructuring?

Desctrcring is an ES6 feature and it's basically a way of unpacking values from an array or object into separate variables.

In other words, Destrctring is a way to break a complex data structure down into a smaller data structure like a variable 

 

For example, before destructuring assignment happes something like below:

//Without Destrcting assign
const arr = [1,2,3]

const a = arr[0];
const b = arr[1];
const c = arr[2];
console.log(x,y,z);
//Output : 1,2,3

Now look below, same thing we can do with destructuring:

////With Destrcting assign
const arr = [1,2,3]

const [x,y,z]= arr;
console.log(x,y,z);
//Output : 1,2,3

 Access Elements using Desctring

Example :1:

const categories: ['angular', 'node', 'java', 'c'];
const [first,second] = categories;
console.log(first,second);
//output : angular,node

Example:2:

const categories: ['angular', 'node', 'java', 'c'];

const[one, , three] = categories;
console.log(one,three);
//output : angular,java

Swapping Values using destructuring:

const categories: ['angular', 'node', 'java', 'c'];

const [first,second] = categories;

[first, second] = [second,first];

console.log(first,second); 

//output : node,angular

Nested destructuring:

const nested = [2,4,[5,6]];
//const[i, , j] = nested;
// console.log(i,j);
//output : 2 , [5,6]

const [i, , [j,k]] = nested;
console.log(i,j,k);
//output : 2 ,5,6

Default Values in destructuring:

// Deafault values
const [p=1,q=1,r=1]  =  [8,9];
console.log(p,q,r);
//output : 8,9,1

 

 

If You Appreciate What We Do Here On TutsCoder, You Should Consider:

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

Leave a Comment