[var1,var2,var3] = array
Let us Understand the use of array destructuring in ES6
In ES5 if the array elements were to be named with a variable instead of accessing them with their index we were supposed to initialize them with variable
Let us take an Example
var arr = [ "one" , "two" , "three" ]/* if we need to access the array elements with variables then we need to initialise them with variables */var a = arr[0];
var b = arr[1];
var c = arr[2];
like this, we were supposed to access the array elements but with array destructuring, this can be skipped
var arr = [ "one" , "two" , "three" ]var [a,b,c] = arr;console.log(`${a} ${b} ${c}`)/*OUTPUT: one two three*/
What if we don't want to assign variables to all the array elements in such case what can be done
var arr = [1,2,3,4,5]/* here we need only refernce to 1'st and last array elemets in such case we can do this */var [a,,,,b] = arr/*
by doing this we have just referneced 1st and last array elements
*/console.log(a)
console.log(b)
EXERCISE — — — — — — — — — — — — — — —
SWAP TWO NUMBERS WITHOUT USING A TEMPORARY VARIABLE
let a = 10 ;
let b = 20 ;[a,b] = [b,a];console.log("value of a is : " + a)
console.log("value of b is : " + b)/*OUTPUT : value of a is : 20
value of b is : 10*/