Array Destructuring

Array Destructuring

Destructuring is an ES6 feature, it’s a way of unpacking values from an array or an object into separate variables. In other words, it means to break a complex data structure down into smaller data structures .. like variables.

For the array, we use destructuring to retrieve elements from the array and store them into variables in a very easy way.

let's see a simple example to understand this :

const arr = [1,2,3]
//if we wanted to retrieve each one of the element in the array into a own variable without destructuring, we can do like this :
const a = arr[0] //1
const b = arr[1] //2
const c = arr[2] //3

//But with destructuring we can actually declare all the 3 variables at the same time. let's see how:
const [x,y,z] = arr;
console.log(x,y,z)//1 2 3

let's see another example of the destructuring array :

Skipping elements:

var arr = ["Hello", "from", "Dev", "With", "Deb"]  

// destructuring assignment  
var [first, second, third, fourth, fifth] = arr;  

console.log(first); // Hello  
console.log(second); // from
console.log(third); // Dev
console.log(fourth); // With
console.log(fifth); // Deb

//We can also log like this :
console.log(first,second,third,fourth,fifth) //Hello from Dev With Deb

// We can also skip the elements
console.log(first, ,second) //Hello Dev 

//Here the second assignment is the third element in the array.(it's like a variable name don't take it otherwise 😉)

Swapping Variables :

Array destructuring makes it easy to swap variables without any temporary variable.

var a = 1, b = 2;  
[a, b] = [b, a];  
console.log(a); // 2  
console.log(b); // 1

What happens when we have a nested array?

Example :

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

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

Default values:

This can be useful when we don't know the length of an array, like when we are fetching any API

//default values
const [p=1,q=1,r=1] = [8]
console.log(p,q,r); //8 1 1

I hope you find it useful, let me know your thoughts on this in the comments. If you have any issues or questions about it, feel free to contact me. Thank you 🌟 for reading! like, share and subscribe to my newsletter for more! 💖

🔗Debasish Lenka

Did you find this article valuable?

Support Debasish Lenka by becoming a sponsor. Any amount is appreciated!