JavaScriptFundamental (ES6), part 1
Map with object and NaN keys in JavaScript
58 A Map keyed by anything, including NaN
fairUse an object, a function, a symbol, a number, a string and NaN as Map keys. Show that lookup is by identity for objects, that 1 and '1' are different keys, that NaN works where indexOf cannot find it, and that -0 and 0 are the same key.
Stuck? Three hints, smallest first
- 1. A Map key can be any value at all, and it is never converted to a string.
- 2. Objects are compared by identity, so an equal-looking literal is a different key.
- 3. Map uses SameValueZero:
NaNequalsNaN, and-0equals0.
const stall = { id: 'stall-1' };
const callback = () => 'noop';
const area = Symbol('area');
const notes = new Map();
notes
.set(stall, 'Balogun')
.set(callback, 'a function key')
.set(area, 'a symbol key')
.set(1, 'the number one')
.set('1', 'the string one')
.set(NaN, 'not a number')
.set(true, 'a boolean key');
const byIdentity = notes.get(stall);
const byLookalike = notes.get({ id: 'stall-1' });
const numberVersusString = [notes.get(1), notes.get('1')];
const nanKey = notes.get(NaN);
const byFunction = notes.get(callback);
const bySymbol = notes.get(area);
const sizeBefore = notes.size;
const indexOfNaN = [NaN, 1].indexOf(NaN);
const findIndexOfNaN = [NaN, 1].findIndex(Number.isNaN);
const includesNaN = [NaN, 1].includes(NaN);
const zeroes = new Map().set(0, 'zero');
const viaMinusZero = zeroes.get(-0);
const removals = [notes.delete(callback), notes.delete(callback)];
const stillThere = notes.has(callback);
console.log('by identity :', byIdentity, '| by a lookalike:', byLookalike);
console.log('1 vs "1" :', numberVersusString);
console.log('NaN as a key :', nanKey, '| indexOf(NaN):', indexOfNaN, '| includes(NaN):', includesNaN);
console.log('-0 finds 0 :', viaMinusZero, '| size:', sizeBefore);
console.log('delete twice :', removals, '| has after:', stillThere);
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 works as a key', byIdentity, 'Balogun');
test('but lookup is by identity, so an equal-looking object misses', byLookalike === undefined, true);
test('the number 1 and the string "1" are two different keys', numberVersusString, ['the number one', 'the string one']);
test('NaN is a usable key, because Map compares with SameValueZero', nanKey, 'not a number');
test('indexOf can never find NaN, though findIndex and includes can', [indexOfNaN, findIndexOfNaN, includesNaN], [-1, 0, true]);
test('minus zero and zero are the same key', viaMinusZero, 'zero');
test('functions and symbols are keys like any other value', [byFunction, bySymbol], ['a function key', 'a symbol key']);
test('size counts the pairs, whatever the keys are', sizeBefore, 7);
test('delete reports whether it removed anything, and has agrees after', [removals, stillThere], [[true, false], false]);
The identity rule cuts both ways. It is what makes a Map the right store for "extra data about this exact object" — a DOM node, a request, a socket — and it is why notes.get({ id: 'stall-1' }) misses: the literal is a different object, however identical it looks. If you want value equality, key on something primitive you derive yourself.
NaN is the pleasant surprise. Map, Set, includes and findIndex all use SameValueZero, under which NaN equals itself, so NaN can be a key and can be found. indexOf is the odd one out: it uses strict equality, and NaN === NaN is false, so it returns -1 for a value that is genuinely in the array. The same rule folds -0 into 0, which is almost always what you want and worth knowing before you rely on the sign.