Array Destructuring in Javascript

Array Destructuring in Javascript

In this tutorial, we are going to learn about array destructuring in javascript.

So, let's get started...

What is Destructuring?

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

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

Also read, Object Destructuring JavaScript

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];
//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;
//Output : 1,2,3

 Access Elements using Desctring

Example :1:

const categories: ['angular', 'node', 'java', 'c'];
const [first,second] = categories;
//output : angular,node


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

const[one, , three] = categories;
//output : angular,java

Swapping Values using destructuring:

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

const [first,second] = categories;

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


//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;
//output : 2 ,5,6

Default Values in destructuring:

// Deafault values
const [p=1,q=1,r=1]  =  [8,9];
//output : 8,9,1


Do let me know If you face any difficulties please feel free to comment below we love to help you.

If you have any feedback suggestions then please inform us by commenting. Don’t forget to share this tutorial with your friends on Facebook and Twitter

Subscribe to our Newsletter

Stay up to date! Get all the latest posts delivered straight to your inbox.

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