JavaScriptFundamental (ES6), part 1
Destructure with defaults, renames and rest in JavaScript
66 Reading an order with defaults, new names and a rest
easyWrite one function that pulls an order apart in its parameter list: rename qty and price, default the ones that are missing, reach into a buyer that may not be there, and sweep every key you did not name into a rest object. Then show what a null does to a default.
Stuck? Three hints, smallest first
- 1. A default in a pattern fires only for
undefined.nullis a value, so it is kept. - 2. Rename and default at once with
qty: quantity = 1, and give the nested pattern its own= {}so a missingbuyerdoes not throw. - 3. The whole parameter needs
= {}too, otherwise calling with no argument at all destructuresundefined.
const readOrder = ({
item,
qty: quantity = 1,
price: kobo = 0,
buyer: { name: buyerName = 'walk-in', phone = null } = {},
...extras
} = {}) => ({ item, quantity, kobo, buyerName, phone, extras });
const full = readOrder({
item: 'garri',
qty: 3,
price: 90000,
buyer: { name: 'Adaeze', phone: '0803' },
market: 'Ikeja',
note: 'coarse',
});
const bare = readOrder({ item: 'yam' });
const nothing = readOrder();
// A default answers "was it undefined", not "was it empty".
const withNull = readOrder({ item: 'rice', qty: null }).quantity;
const withZero = readOrder({ item: 'rice', qty: 0 }).quantity;
// Destructuring undefined is a TypeError, which is why the = {} is there.
let cracked;
try {
const { item } = undefined;
cracked = item;
} catch (error) {
cracked = error.constructor.name;
}
// Renaming moves the binding: the source key never becomes a variable.
const sourceKeyInScope = typeof qty;
console.log('full :', full);
console.log('bare :', bare);
console.log('nothing:', nothing.item, nothing.quantity, nothing.buyerName);
console.log('null vs zero:', withNull, withZero, '| undefined:', cracked);
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('every named key lands in its new name', [full.item, full.quantity, full.kobo, full.buyerName], ['garri', 3, 90000, 'Adaeze']);
test('the rest holds only the keys the pattern did not name', full.extras, { market: 'Ikeja', note: 'coarse' });
test('defaults fill the gaps in a bare order', [bare.quantity, bare.kobo, bare.buyerName, bare.phone], [1, 0, 'walk-in', null]);
test('and = {} on the parameter lets it be called with nothing at all', [nothing.item ?? 'none', nothing.quantity, nothing.buyerName], ['none', 1, 'walk-in']);
test('a default fires for undefined only, so null survives and 0 survives', [withNull, withZero], [null, 0]);
test('without that default, destructuring undefined throws', cracked, 'TypeError');
test('renaming does not leave the old name behind', sourceKeyInScope, 'undefined');
test('a nested pattern with its own default survives a missing branch', readOrder({ item: 'ewa' }).phone, null);
A parameter pattern is documentation the engine enforces. Everything a caller may leave out has its default written where you read it, and everything you did not plan for is still there in extras rather than silently dropped.
The trap is the word "missing". A pattern default is triggered by undefined and nothing else, so { qty: null } gives you null, not 1, and a row that came back from a database with real nulls in it walks straight past every default you wrote. If you want null handled too, follow the destructure with ??, which treats null and undefined alike.
The two = {} defaults are load-bearing in different places. The one on the parameter makes readOrder() legal; the one after buyer: makes an order without a buyer legal. Leave either out and you get the same TypeError the try above catches, because reading a property of undefined is exactly what a pattern does.