JavaScriptFundamental (ES6), part 1
The == coercion table in JavaScript
146 the == table, pair by pair
hardBuild a table of the comparisons that catch people out and assert every entry: null against undefined, false and 0; null >= 0 next to null > 0; empty and whitespace strings against 0; the three pairs that show == is not transitive; arrays against booleans, numbers and strings, including [] == ![]; and NaN and -0 under ==, === and Object.is. Then run the whole list through === and say how many survive.
Stuck? Three hints, smallest first
- 1.
==between different types converts to NUMBER, with one carve-out:nullandundefinedequal each other and nothing else, with no conversion at all. - 2. An object is converted by
valueOfthentoString, so an array becomes itsjoin(',')string first and only then a number. - 3.
>=is not>negated, and it does not share the==carve-out: it convertsnullto0.
const nullish = {
'null == undefined': null == undefined,
'null === undefined': null === undefined,
'null == false': null == false,
'null == 0': null == 0,
'null == empty string': null == '',
};
const relational = {
'null >= 0': null >= 0,
'null > 0': null > 0,
'null <= 0': null <= 0,
'undefined >= 0': undefined >= 0,
};
const emptyish = {
'empty string == 0': '' == 0,
'space == 0': ' ' == 0,
'newline == 0': '\n' == 0,
'zero string == 0': '0' == 0,
'empty string == zero string': '' == '0',
};
const notTransitive = ['0' == 0, 0 == '', '0' == ''];
const boolish = {
'zero string == false': '0' == false,
'empty string == false': '' == false,
'one string == true': '1' == true,
'2 == true': 2 == true,
'empty array == false': [] == false,
'empty array == not empty array': [] == ![],
};
const arrays = {
'[1] == 1': [1] == 1,
'empty array == empty string': [] == '',
'array of empty array == empty string': [[]] == '',
'[null] == empty string': [null] == '',
'[undefined] == empty string': [undefined] == '',
"[1,2] == '1,2'": [1, 2] == '1,2',
};
const objects = {
'plain object == its toString': ({}) == '[object Object]',
'two empty arrays': [] == [],
'two empty objects': ({}) === ({}),
};
const nanFacts = [NaN == NaN, NaN === NaN, Object.is(NaN, NaN), Number.isNaN(NaN)];
const zeroFacts = [0 === -0, 0 == -0, Object.is(0, -0), [0, -0].map((n) => 1 / n === Infinity)];
const coercions = [Number(''), Number(' '), Number(null), Number([]), Number([2]), String(Number(undefined))];
const everySurprise = [null == undefined, '' == 0, '0' == 0, [] == false, [1] == 1, ({}) == '[object Object]'];
const sameWithTripleEquals = [null === undefined, '' === 0, '0' === 0, [] === false, [1] === 1, ({}) === '[object Object]'];
console.log('nullish :', nullish);
console.log('relational:', relational);
console.log('emptyish :', emptyish, '| transitive?', notTransitive);
console.log('boolish :', boolish);
console.log('arrays :', arrays, '| objects:', objects);
console.log('NaN / -0 :', nanFacts, zeroFacts, '| Number():', coercions);
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('null and undefined are loosely equal to each other and to nothing else', Object.values(nullish), [true, false, false, false, false]);
test('but the relational operators do not share that rule, so null is both >= 0 and not > 0', Object.values(relational), [true, false, true, false]);
test('any whitespace-only string becomes 0, and these are the conversions doing it', [Object.values(emptyish), coercions], [[true, true, true, true, false], [0, 0, 0, 0, 2, 'NaN']]);
test('so == is not transitive: two pairs equal, the third not', notTransitive, [true, true, false]);
test('a boolean is converted to a number too, which is why 2 is not true', Object.values(boolish), [true, true, true, false, true, true]);
test('an array stringifies before it numifies, so all six of these hold', Object.values(arrays), [true, true, true, true, true, true]);
test('an object equals its own toString, but two objects are compared by identity', Object.values(objects), [true, false, false]);
test('NaN alone is not equal to itself, and -0 is where === and Object.is part company', [nanFacts, zeroFacts], [[false, false, true, true], [true, true, false, [true, false]]]);
test('every surprise above disappears under ===', [everySurprise, sameWithTripleEquals], [[true, true, true, true, true, true], [false, false, false, false, false, false]]);
The algorithm is short enough to memorise, which is better than memorising the table. If the types match, == is ===. If one side is null and the other undefined, the answer is true and nothing is converted — that is the whole reason null == 0 is false while null >= 0 is true, since the relational operators have no such carve-out and quietly turn null into 0. Otherwise both sides are converted toward number: a boolean becomes 0 or 1, so 2 == true is false; a string is parsed, and a string of nothing but whitespace parses to 0; an object is asked for a primitive via valueOf then toString.
That last step is what makes arrays so strange. [] has no useful valueOf, so toString gives join(','), which is the empty string, which becomes 0. Hence [] == false, [] == 0 and [[]] == ''. [] == ![] is the same fact wearing a costume: ! binds tighter, ![] is false, and the comparison is [] == false. And because null and undefined stringify to nothing inside join, [null] == '' too.
Non-transitivity is the killer argument. '0' == 0 and 0 == '', yet '0' != '', because each comparison converts differently and no consistent notion of equality survives. Use ===, which as the final assertion shows collapses every row to false. Keep exactly one == in your vocabulary, x == null, as the terse test for null-or-undefined. For the two edges === gets wrong, use Number.isNaN rather than x !== x, and remember Object.is is not simply a better ===: it disagrees on NaN and on -0, and on nothing else.