JavaScriptFundamental (ES6), part 1
Computed property keys in JavaScript
34 Computed keys and what a key really is
fairBuild an object whose keys come from expressions, then find out what happens when the key is a number, an object, or a symbol. Check how many times the key expression is evaluated.
Stuck? Three hints, smallest first
- 1. Square brackets in a literal make the key an expression:
{ [name]: value }. - 2. Every key is a string except a symbol. A number, an object, anything else is converted first.
- 3. An object converts through its
toString, which is why two different objects can collide on one key.
const field = 'rentNgn';
const record = { [field]: 12000, [field + 'Paid']: true, ['A' + 1]: 'stall' };
const numeric = { 1: 'one' };
const asKey = { toString: () => 'custom' };
const bag = { [asKey]: 'from an object' };
const k1 = {};
const k2 = {};
const collided = { [k1]: 'first' };
collided[k2] = 'second'; // a different object, the same key
const id = Symbol('id');
const withSymbol = { [id]: 'hidden', plain: 'visible' };
let evaluated = 0;
const keyName = () => { evaluated++; return 'once'; };
const timed = { [keyName()]: true };
console.log('computed keys :', Object.keys(record));
console.log('numeric key :', Object.keys(numeric), numeric[1] === numeric['1']);
console.log('object as key :', Object.keys(bag));
console.log('collision :', Object.keys(collided), '->', collided[k1]);
console.log('symbol :', withSymbol[id], '| visible keys:', Object.keys(withSymbol));
console.log('evaluations :', evaluated);
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 computed key is the value of the expression', Object.keys(record), ['rentNgn', 'rentNgnPaid', 'A1']);
test('a numeric key is stored as a string', Object.keys(numeric), ['1']);
test('so obj[1] and obj["1"] are one property', numeric[1] === numeric['1'], true);
test('an object key goes through toString', Object.keys(bag), ['custom']);
test('so two different objects collide on a single key', [Object.keys(collided).length, collided[k1]], [1, 'second']);
test('a symbol is the one key that is not converted', withSymbol[id], 'hidden');
test('and it is invisible to Object.keys', Object.keys(withSymbol), ['plain']);
test('the key expression is evaluated once, as the literal is built', [evaluated, Object.keys(timed)], [1, ['once']]);
Computed keys removed the last reason to build an object in two steps — const o = {}; o[k] = v; — so a lookup table can be a single expression, which matters when it is const.
The collision assertion is the argument for Map. An object property name is always a string or a symbol, so using objects as keys silently funnels every one of them into '[object Object]'. A Map keys on identity, so two empty objects are two entries. Symbols are the escape hatch in the other direction: a symbol key cannot collide with anyone else's and does not show up in Object.keys, for...in or JSON.stringify.