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);

nested

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');

interesting

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);

Required Knowledge

Related Katas

Destructuring

Difficulty Level

BEGINNER

First Published

30 March 2015

Stats

6 tests to solve