DryKiss

Destructuring in JS


Destructuring is a convenient way in Javascript to extract multiple values from data stored in Arrays and properties stored in Objects into distinct variables using a single line of assignment expression!

In short: Use one assignment expression to assign all array / object data members to individual variables.

Big reason why you should learn and use ES6!

Quick Examples

: Arrays :

var exampleArray, a, b, c, d;

// Array to multiple variables =>
exampleArray=[23, 'Hello', true, 0];
[a, b, c, d] = exampleArray;

console.log(a,b,c,d); // 23 "Hello" true 0

// Or better still combine declaration & assignment using this syntax =>
var [a,b,c,d] = exampleArray;

console.log(a,b,c,d); // 23 "Hello" true 0

: Objects :

let obj = { a: 'Hello', b: 14, c: true};

let {a,b,c} = obj; // destructuring the 'obj' object

console.log(a,b,c); // Hello 14 true
DryKiss. Web Dev, Physics, Math, Philosophy and Photography
About author. Computer Scientist and a wannabe Physicist