JS - Best Practices (Destructuring)

 

Destructuring allows to extract values from arrays and objects (even deeply nested) and store them in variables with a more convenient syntax.

 

Destructuring Arrays :

Old :

var arr = [1, 2, 3, 4];
var a = arr[0];
var b = arr[1];
var c = arr[2];
var d = arr[3];

ES6:

let [a, b, c, d] = [1, 2, 3, 4];   

console.log(a); // 1
console.log(b); // 2

 

Destructuring Objects :

Old :

var luke = { occupation: 'jedi', father: 'anakin' };       
var occupation = luke.occupation; // 'jedi'
var father = luke.father; // 'anakin'

ES6:

let luke = { occupation: 'jedi', father: 'anakin' };
let {occupation, father} = luke;

console.log(occupation); // 'jedi'
console.log(father); // 'anakin'

 
Read More:
http://exploringjs.com/es6/ch_destructuring.html
 
 

js best practices