jskatas.org Continuously Learn JavaScript. Your Way.

Destructuring: object

Destructuring objects is a core concepts for modules and more.

Destructure objects

by surrounding the left-hand variable with {}
const x = {x: 1}; assert.equal(x, 1);


multiple objects
const magic = {first: 23, second: 42}; const {magic: [second]} = {magic}; assert.equal(second, 42);
object and array
const {z:[x]} = {z: [23, 42]}; assert.equal(x, 42);
array and object
const [,{lang}] = [null, [{env: 'browser', lang: 'ES6'}]]; assert.equal(lang, 'ES6');


missing refs become undefined
const {z} = {x: 1, z: 2}; assert.equal(z, void 0);
destructure from builtins (string)
const {substr} = 1; assert.equal(substr, String.prototype.substr);