JavaScriptFundamental (ES6), part 1
Default values in object destructuring in JavaScript
21 Defaults in an object pattern
fairGive object pattern keys defaults and check which values trigger them. Then combine renaming with a default, chain one default off another, and put a default on an intermediate object so a missing nesting does not throw.
Stuck? Three hints, smallest first
- 1. Same rule as the array form: the default fires on
undefinedonly. - 2. Renaming and defaulting combine as
{ key: newName = fallback }. - 3. A default may sit on any part of the pattern, including the object in the middle of a nesting.
const opts = { retries: 0, label: null, area: undefined };
const { retries = 3 } = opts;
const { label = 'unnamed' } = opts;
const { area = 'Yaba' } = opts;
const { branch = 'Ikeja' } = opts; // key absent entirely
const { rentNgn: rent = 0 } = {}; // rename and default together
const { width = 2, height = width * 3 } = {}; // chained
const { limits: { daily } = { daily: 50000 } } = {}; // the nesting is missing
const { limits: { daily: dailyPresent } = { daily: 0 } } = { limits: { daily: 999 } };
console.log('zero kept :', retries);
console.log('null kept :', label);
console.log('undefined value:', area, '<- default fired');
console.log('absent key :', branch);
console.log('rename+default :', rent);
console.log('chained :', width, height);
console.log('nested default :', daily, '| ignored when present:', dailyPresent);
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a default fills a key that is not there', branch, 'Ikeja');
test('and a key whose value is undefined', area, 'Yaba');
test('but never one that is null', label, null);
test('nor a zero, which is a perfectly good setting', retries, 0);
test('rename and default combine as key: name = fallback', rent, 0);
test('a later default may read an earlier binding', [width, height], [2, 6]);
test('a default on the middle object survives a missing nesting', daily, 50000);
test('and is ignored when the nesting is there', dailyPresent, 999);
{ rentNgn: rent = 0 } packs three decisions into eight characters: which key to read, what to call it, and what to use when it is absent. Read it left to right and it stays clear; write it the other way round ({ rent = 0: rentNgn }) and it is a syntax error.
The default on the intermediate object is the useful trick here. { limits: { daily } = {} } turns a nested read that would have thrown into one that quietly yields undefined — the same job optional chaining does for a dotted read.