
Destructuring assignment
Destructuring assignment syntax allows you to unpack values from arrays or object properties and assign them to different variables. I like this syntax because it makes the code more readable and streamlines variable/property assignments.
Arrays
Separate variable declaration:
let a, b, c;
[a,b,c] = ['2',5,'test'];
console.log(a);
console.log(b);
console.log(c);
//'2'
//5
//'test'If you want to concatenate an array it can be done like this
[a,b, ...more] = ['2',5,'test',20,'another test', [1,2]];
//a = '2'
//b = 5
//more = ['test',20,'another test', [1,2]]Variable Assignment:
const data = [1,2,3,4];
const [a,b,c,d] = data;
console.log(a);//1
console.log(b);//2
console.log(c);//3
console.log(d);//4Default Values:
You can set default values to variables and override the values with destructuring assignment.
let x,y;
[x=3,y=2] = ['2'];
console.log(x); // '2'
console.log(y); // 2Swap Values:
let x = 12;
let y = "NYC";
[x,y] = [y,x];
//x = 'NYC'
//y = 12
const arr = ['LA',2,'NYC'];
[arr[2], arr[0]] = [arr[0], arr[2]];
console.log(arr); // ['NYC',3,'LA']Objects
let student_1 = {name: 'Sam'};
let student_2 = {name: 'David'};
let {name: new_student_1} = student_1;
let {name: new_student_2} = student_2;
console.log(new_student_1);
//'Sam'
console.log(new_student_2);
//'David'If the property and the variable are have the same name you can use this shortcut:
var { firstName, age } = { firstName: "Cookie", age: 32 };
console.log(firstName);
// "Cookie"
console.log(age);
// 32Nesting properties:
let newObj = {
data: [ {id: 4}, 'Walking']
};
var { data: [{id}, transportation ] } = newObj;
console.log(id);
//4
console.log(transportation);
//'Walking'
If you try to destructure on properties that are not defined undefined with be be returned.
let { last } = {};
console.log(last);
//undefinedFor a deep dive into destructuring click here .