JavaScriptFundamental (ES6), part 1
Destructuring undefined and computed keys in JavaScript
25 Destructuring nothing, and computed keys
hardFind out what destructuring null and undefined does, whether an empty pattern is any safer, and what happens on a number or a string. Then read a property whose name is only known at runtime.
Stuck? Three hints, smallest first
- 1. Destructuring converts the right-hand side to an object first, and
nullandundefinedcannot be converted. - 2. A primitive can be, so
const { length } = 'Lagos'works through the wrapper object. - 3. Square brackets in a pattern take an expression as the key:
const { [name]: value } = obj.
const attempt = (fn) => {
try { return fn(); } catch (e) { return e.constructor.name; }
};
const fromNull = attempt(() => { const { a } = null; return a; });
const fromUndefined = attempt(() => { const { a } = undefined; return a; });
const emptyOnNull = attempt(() => { const {} = null; return 'no throw'; });
const emptyOnString = attempt(() => { const {} = 'anything'; return 'no throw'; });
const arrayOnNull = attempt(() => { const [only] = null; return only; });
const { length: townLength } = 'Lagos';
const { toFixed } = 12000;
const field = 'rentNgn';
const { [field]: rent } = { rentNgn: 12000 };
const { [field.toUpperCase()]: shouted = 'none' } = { RENTNGN: 'loud' };
let reads = 0;
const keyOf = () => { reads++; return 'code'; };
const { [keyOf()]: code } = { code: 'A1' };
console.log('null :', fromNull, '| undefined:', fromUndefined);
console.log('empty {} :', emptyOnNull, 'on null,', emptyOnString, 'on a string');
console.log('array on null:', arrayOnNull);
console.log('primitives :', townLength, typeof toFixed);
console.log('computed :', rent, '| with an expression:', shouted);
console.log('key reads :', reads, '->', code);
Output
9 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 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('an object pattern on null throws', fromNull, 'TypeError');
test('and on undefined', fromUndefined, 'TypeError');
test('an empty pattern is no protection at all', emptyOnNull, 'TypeError');
test('though on a primitive it is legal and binds nothing', emptyOnString, 'no throw');
test('an array pattern on null throws for the same reason', arrayOnNull, 'TypeError');
test('a primitive is wrapped, so its properties come out', townLength, 5);
test('methods included', typeof toFixed, 'function');
test('a computed key reads the property an expression names', rent, 12000);
test('and the key expression is evaluated exactly once', [reads, code], [1, 'A1']);
Every pattern begins with a coercion to object. null and undefined are the two values that cannot be coerced, so they throw — and const {} = null throws too, which shows the failure is the conversion, not the properties. That is why const { data } = await res.json() is a real hazard: one empty body and the destructure is the crash site.
Computed keys make a pattern dynamic, but the name has to be known by the time the line runs, and the binding still needs a name you write by hand. If keys are genuinely arbitrary, you want Object.entries or a Map, not a pattern.