Skip to content

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.

13 min read0/5 questions

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 is false. No conversion happens.
  • == (loose equality) first coerces (converts) the two values to a common type, then compares.
JavaScript
console.log(1 === 1, "1" === 1);console.log(1 == "1"); // the string becomes a numberconsole.log(0 == ""); // "" becomes 0console.log(0 == false); // false becomes 0console.log(null == undefined, null === undefined);console.log(null == 0); // null only loosely equals undefined
Output
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.

Predict the outputJavaScript

What does this print?

console.log("5" == 5);
console.log("5" === 5);
console.log([] == false);
console.log(null == false);
Need a nudge? Hints walk you through it.

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 valueType
falseboolean
0, -0number
0nbigint
"" (empty string)string
nullnull
undefinedundefined
NaNnumber

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.

JavaScript
const values = [ ["0", 0], ['"0"', "0"], ['""', ""], ['" "', " "], ["[]", []], ["{}", {}], ["null", null], ["NaN", NaN], ['"false"', "false"], ["-1", -1],];for (const [label, v] of values) { console.log(label.padEnd(8), Boolean(v));}
Output
Press Run (⌘ Enter) to see what happens.
Quick checkPick all that apply
Which of these values are truthy? Pick all that apply.

None picked yet

Need a nudge? A hint rules out a wrong answer.

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.

JavaScript
function showStock(qty) { if (!qty) return "Unknown"; // bug: 0 is a real quantity return `${qty} left`;}function showStockFixed(qty) { if (qty === undefined || qty === null) return "Unknown"; return `${qty} left`;} console.log(showStock(0), "|", showStockFixed(0));console.log(showStock(undefined), "|", showStockFixed(undefined));
Output
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, NaNfalsetrue
0, -0truefalse
1, 1truetrue

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.

Same contents, different objects
const a = { x: 1 };
NamesObjects in memoryaobject{ x: 1 }

The object literal creates an object in memory. a holds a reference to it (an arrow, not the object itself).

1/4
Predict the outputJavaScript

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));
Need a nudge? Hints walk you through it.

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:

  1. If Object.is(a, b), they are equal.
  2. If either is not an object (or is null), they are not equal.
  3. If one is an array and the other is not, not equal.
  4. Compare key counts, then recursively compare each key's value.
Put it in order5 steps

Order the checks inside a deepEqual(a, b) function.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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.

JavaScript
console.log("10" < "9"); // string comparisonconsole.log("10" < 9); // number comparisonconsole.log([10, 9, 1].sort());console.log([10, 9, 1].sort((a, b) => a - b));
Output
Press Run (⌘ Enter) to see what happens.
Quick check
Why does ["b", "a", "C"].sort() return ["C", "a", "b"]?
Need a nudge? A hint rules out a wrong answer.
ChallengeMedium

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, {});                               // false

You only need to handle primitives, arrays and plain objects.

JavaScript
function deepEqual(a, b) { // Cheap checks first, then recurse into arrays and objects. return false;}
ChallengeEasy

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.

JavaScript
function removeMissing(values) { // Keep a value unless it is null or undefined. return values;}
Key terms
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 treats NaN as equal to itself and distinguishes 0 from -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.