jskatas.org Continuously Learn JavaScript. Your Way.

Destructuring: parameters

Destructuring function parameters.

Destructuring function parameters

destruct parameters

multiple params from object
const fn = ({id}, {name}) => { assert.equal(id, 42); assert.equal(name, 'Wolfram'); }; const user = {name: 'Wolfram', id: 42}; fn(user);
multiple params from array/object
const fn = ([{name}]) => { assert.equal(name, 'Alice'); }; const users = [{name: 'nobody'}, {name: 'Alice', id: 42}]; fn(users);

default values

for simple values
const fn = (id, name='Bobby') => { assert.strictEqual(id, 23); assert.strictEqual(name, 'Bob'); }; fn(23);
for a missing array value
const defaultUser = {id: 23, name: 'Joe'}; const fn = ([user]) => { assert.deepEqual(user, defaultUser); }; fn([]);
mix of parameter types
const fn = (id, [arr], {obj}) => { assert.equal(id, 1); assert.equal(arr, 2); assert.equal(obj, 3); }; fn(void 0, [], {});

Required Knowledge

Related Katas

Destructuring

Difficulty Level

INTERMEDIATE

First Published

1 April 2015

Stats

5 tests to solve