JavaScript Array Destruction Tutorial With Realtime Examples

Array and object destruction is very useful in JavaScript. We can extract variables out of an array. 

let data = [1,2,3,4]
let [num1,num2,num3,num4] = data
console.log(num1, num2, num3, num4)

We can also skip a few array indexes and assign values to variables like this. 

let names = ['John', 'Jessica', 'Bill', 'Adam', 'Helen']
let [name1,name2,,,name5] = names
console.log(name1, name2, name5)

We can also assign default values to the variables and they will adjust according to the array. 

let numbers = [ 5, 6 ]
let [num1 = 0,num2 = 0, num3 = 0 ] = numbers
console.log(num1, num2, num3)

Here is a very interesting thing to do. We can swap values of numbers using array destruction. 

let a = 5, b = 10;
[a,b] = [b,a]
console.log(a)
console.log(b)

Now there are 2 concepts in array destruction. Spread and Rest operators. They make our life very easy. We can pass as many variables in a function and catch it as an array. 

function showNumbersArray(...numbers){
    return numbers;
}
console.log(showNumbersArray(1,2,3,4,5,6,7,8,9))

So here by using the spread operator we just converted all the numbers into the array. 

Now we can destruct arrays also using the spread operator. 

function showNumbers(num1, num2, num3, num4){
    console.log( num1, num2, num3, num4);
}
showNumbers(...[1,2,3,4,5,6,7,8,9])

Now we can destruct a few variables and copy others in another array. Here is an example of id and name with steps for some user and we are destructing this array into variables and another array. 

let [id, name, ...steps] = [112,'Harper',3,4,5,6,7,8,9];
console.log(id)
console.log(name)
console.log(steps)

I hope these tricks will help you.