Friday, January 6, 2023

Destructuring Arrays

/*** Destructuring Arrays ***/
let myArray = [100,200,300];
let myArray2 = [500,[10,20]]

// Destructuring array into each variable
let [a,b,c] = myArray;
console.log(a, b, c); // 100 200 300

// Destructuring only required elements 
const [x,,y] = myArray;
console.log(x,y); // 100 300

// Default Values while destructuring
const [p, q, r, s = 0] = myArray;
console.log(p, q, r, s); // 100 200 300 0

// Exchanging the variable values
[c, b, a] = [a, b, c];
console.log(a, b, c); // 300 200 100

// Destructuring the nested array
const [i,[j,k]] =  myArray2; 

console.log(i,j,k); // 500 10 20 

No comments:

Post a Comment