Destructuring

destructuring

Destructuring

Destructuring is a way to quickly extract data out of an {} or [] without having to write much code.

ES5 Way


let foo = ['x', 'y', 'z'];

let a   = foo[0];
let b   = foo[1];
let c = foo[2];

ES6 Way


let foo = ['x', 'y', 'z'];
let [a, b, c] = foo;
console.log(a); // 'one'

We can use this for object destructuring.


let math = {
	add: function(a, b) { return a+b; },
	sub: function(a, b) { return a-b; }
};


let {add, sub} = math;

add(2, 3);
sub(5, 3); 

Another use case is we can use also be used for passing objects into a function, allowing you to pull specific properties out of an object in a concise manner.


let a = { firstName: "A", lastName: "X" };
let b = { firstName: "B", lastName: "Y" };


function sayName({firstName, lastName, middleName = 'N/A'}) {
	console.log(`Hello ${firstName} ${middleName} ${lastName}`)  
}

sayName(a) //  Hello A N/A X
sayName(b) // Helo B Smith Y

You May Also Like

About the Author: Pankaj Bisht