Lesson 9 of 50JavaScript basics
Equality and Truthiness
Compare values correctly with ===, predict coercion, know the falsy list, and compare objects by value when you need to.
if (count) skipping a count of zero, [] == false being true, two identical-looking objects that are "not equal": these are the bugs that make people say JavaScript is weird. Each one follows a small set of rules. Learn the rules once and you can predict every case, which is exactly what interviewers test with "what does this print?" questions.
=== and ==
JavaScript has two equality operators.
===(strict equality) compares type and value. If the types differ, the answer isfalse. No conversion happens.==(loose equality) first coerces (converts) the two values to a common type, then compares.
Press Run (⌘ Enter) to see what happens.The rules for == fill a page of the spec. The short version: booleans become numbers, strings become numbers when compared with numbers, objects are turned into primitives (an array becomes its joined string), and null and undefined equal each other but nothing else.
Use === everywhere. ESLint's eqeqeq rule enforces it. The one common exception is value == null, a deliberate shortcut that is true for both null and undefined. Some teams allow it; many prefer the explicit value === null || value === undefined.
What does this print?
console.log("5" == 5);
console.log("5" === 5);
console.log([] == false);
console.log(null == false);Truthy and falsy
if, while, &&, ||, ! and the ternary all convert their condition to a boolean. A value that converts to false is falsy. There are exactly eight falsy values, and everything else is truthy:
| Falsy value | Type |
|---|---|
false | boolean |
0, -0 | number |
0n | bigint |
"" (empty string) | string |
null | null |
undefined | undefined |
NaN | number |
Memorise the list rather than the exceptions. Things that surprise people because they are truthy: "0", "false", " " (a space), [] (an empty array) and {} (an empty object). Python treats empty lists and dicts as falsy; JavaScript does not.
Press Run (⌘ Enter) to see what happens.None picked yet
The zero bug
Truthiness checks are great for "is there a value at all?" and wrong for "is the value missing?" when 0 or "" is a valid value.
Press Run (⌘ Enter) to see what happens.The same bug appears in React: {items.length && <List />} renders a literal 0 on the page when the list is empty, because 0 && x evaluates to 0. Write {items.length > 0 && <List />}.
Object.is and the odd numbers
=== has two edge cases. NaN === NaN is false, and 0 === -0 is true. Object.is(a, b) fixes both: it treats NaN as equal to itself and tells 0 and -0 apart. Otherwise it behaves like ===.
| Expression | === | Object.is |
|---|---|---|
NaN, NaN | false | true |
0, -0 | true | false |
1, 1 | true | true |
You rarely call it yourself, but React uses Object.is to decide whether state changed, and Array.prototype.includes uses a similar rule (so [NaN].includes(NaN) is true while [NaN].indexOf(NaN) is -1).
Comparing objects: references
For objects, === (and ==) compare references, not contents. Two objects are equal only if they are the very same object in memory.
The object literal creates an object in memory. a holds a reference to it (an arrow, not the object itself).
What does this print?
const a = [1, 2]; const b = [1, 2]; const c = a; console.log(a === b, a === c); console.log(JSON.stringify(a) === JSON.stringify(b));
Deep equality
To compare by contents you need deep equality: walk both values and compare every nested property. JSON.stringify(a) === JSON.stringify(b) works for quick checks but breaks when key order differs ({a:1, b:2} vs {b:2, a:1}), and it drops undefined values and functions. Test libraries ship a proper version (expect(x).toEqual(y) in Jest and Vitest), and Node has util.isDeepStrictEqual. The algorithm is a classic interview question, and it is your challenge below:
- If
Object.is(a, b), they are equal. - If either is not an object (or is
null), they are not equal. - If one is an array and the other is not, not equal.
- Compare key counts, then recursively compare each key's value.
Order the checks inside a deepEqual(a, b) function.
- Tap the steps below in the right order.
Sorting numbers, revisited
Comparison rules explain the sort trap from the arrays lesson. sort() with no comparator turns every element into a string and compares strings, where "10" < "9" because "1" comes before "9". Relational operators (<, >) coerce too: comparing two strings is alphabetical, comparing a string with a number converts the string.
Press Run (⌘ Enter) to see what happens.["b", "a", "C"].sort() return ["C", "a", "b"]?deepEqual
=== compares objects by reference. Write deepEqual(a, b) that compares by contents: primitives must be equal (Object.is), arrays must have equal items in the same order, and objects must have the same set of keys with deeply equal values (key order does not matter).
deepEqual({ a: 1, b: [1, 2] }, { b: [1, 2], a: 1 }); // true
deepEqual([1, 2], [2, 1]); // false
deepEqual([], {}); // false
deepEqual(null, {}); // falseYou only need to handle primitives, arrays and plain objects.
Remove missing values
A form returns an array of answers. Some are missing (null or undefined), but 0, "", false and even NaN are real answers the user gave. Write removeMissing(values) that returns a new array without the null and undefined entries, keeping everything else in order.
removeMissing([0, null, "", false, undefined, "yes"]); // [0, "", false, "yes"]A truthiness filter like values.filter(Boolean) is the bug this exercise is about.
- strict equality (===)
- Compares type and value with no conversion. The default choice.
- loose equality (==)
- Coerces both sides to a common type first. Avoid it, except possibly
x == null. - falsy
- Converts to
false:false,0,-0,0n,"",null,undefined,NaN. Everything else is truthy. - Object.is
- Like
===but treatsNaNas equal to itself and distinguishes0from-0. React uses it to detect state changes. - reference equality
- Objects are equal with
===only when both sides point at the same object in memory. - deep equality
- Comparing objects by recursively checking that all nested keys and values match.