Sub topic 2
Comparing Values: === vs == and Relational Operators
Every if statement and every loop condition you write later in this tutorial depends on a comparison. JavaScript has two equality operators that behave differently. Its relational operators (<, >, <=, >=) also have conversion rules that can surprise you. This chapter explains how each operator works, where each one goes wrong, and which one to use.
This chapter assumes you can declare variables with let and const and that you know the primitive types (number, string, boolean, null, undefined) as well as arrays and plain objects. It also builds on the previous chapter's idea of truthy and falsy values.
Strict Equality: ===
The strict equality operator === compares two values without converting either one. If the types differ, the result is false. If the types match, it compares the values.
console.log(0 === ""); // false: number vs string
console.log(1 === 1); // true
console.log("abc" === "abc"); // true
console.log(null === undefined); // false: different types
console.log(true === 1); // false!== is the negated form, and it follows the same rules.
The Two Exceptions Inside ===
Strict equality has two quirks that come from how floating-point numbers work:
NaN === NaNisfalse.NaNis the only value that is not equal to itself.0 === -0istrue, even though the two are different values internally.
const result = Number("hello"); // NaN
console.log(result === NaN); // false, always
console.log(Number.isNaN(result)); // true
console.log(Object.is(NaN, NaN)); // true
console.log(Object.is(0, -0)); // falseTo test for NaN, use Number.isNaN. Object.is is a third kind of equality. It behaves like === but handles these two cases the other way round. You will rarely need it outside library code.
Objects Compare by Reference
For arrays, objects, functions, and dates, === checks whether both sides are the same object in memory. It does not compare their contents.
const a = [1, 2];
const b = [1, 2];
const c = a;
console.log(a === b); // false: two separate arrays
console.log(a === c); // true: same array
const d1 = new Date(2026, 0, 1);
const d2 = new Date(2026, 0, 1);
console.log(d1 === d2); // false
console.log(d1.getTime() === d2.getTime()); // trueIf you need to compare contents, compare the parts yourself. For dates, compare the timestamps.
Loose Equality: ==
The loose equality operator == converts its operands to a common type when their types differ, and then compares them. This conversion is called type coercion. The rules are fixed, but there are enough of them that the results are hard to predict.
console.log(0 == ""); // true
console.log(1 == "1"); // true
console.log(true == "1"); // true
console.log(null == undefined); // true
console.log(null == 0); // false
console.log([1, 2] == "1,2"); // trueHow the Coercion Works
The diagram shows a simplified version of the algorithm. BigInt and Symbol cases are left out.
Following the steps explains the strange results:
| Expression | Steps | Result |
|---|---|---|
| `0 == ""` | `""` becomes `0`, then `0 == 0` | `true` |
| `"0" == false` | `false` becomes `0`, `"0"` becomes `0` | `true` |
| `[] == false` | `false` becomes `0`, `[]` becomes `""`, then `0` | `true` |
| `[] == ![]` | `![]` is `false`, then same as above | `true` |
| `null == 0` | `null` only loosely equals `undefined` | `false` |
| `" \n" == 0` | whitespace-only string becomes `0` | `true` |
Loose Equality Disagrees with Truthiness
The booleans row in the table causes real bugs. When you compare with true or false using ==, the boolean becomes a number. JavaScript does not check truthiness here.
const value = "0";
if (value) {
console.log("truthy"); // runs: non-empty strings are truthy
}
if (value == false) {
console.log("also loosely equal to false"); // also runs
}
const items = [2];
console.log(items == true); // false: true becomes 1, [2] becomes 2The One Common Use: == null
Under the rules above, x == null is true only when x is null or undefined. It is false for 0, "", false, and NaN. That makes it a short way to check for a missing value:
function describe(x) {
return x == null ? "missing" : "present";
}
console.log(describe(undefined)); // "missing"
console.log(describe(null)); // "missing"
console.log(describe(0)); // "present"
console.log(describe("")); // "present"Some style guides allow this one idiom and ban every other use of ==. ESLint's eqeqeq rule has a "smart" option, and { "null": "ignore" } permits exactly this case. If your team prefers no exceptions, write x === null || x === undefined.
Relational Operators: <, >, <=, >=
Relational operators also convert their operands, and their rules differ from those of ==.
- Both operands are converted to primitives. Arrays and objects become strings, and dates become numbers.
- If both primitives are strings, they are compared character by character using UTF-16 code unit values.
- Otherwise, both are converted to numbers and compared numerically. If either side is
NaN, the result isfalse.
String vs Numeric Comparison
console.log("10" < "9"); // true: "1" comes before "9"
console.log("10" < 9); // false: numeric, 10 < 9
console.log("Zebra" < "apple"); // true: "Z" is 90, "a" is 97
console.log([2] > 1); // true: [2] -> "2" -> 2The "10" < "9" case often appears when values come from form inputs, URL parameters, or CSV files, because all of those arrive as strings. Convert them with Number() before you compare.
const minAge = "18"; // read from a form field
const age = "9";
console.log(age < minAge); // false: string comparison, "9" > "1"
console.log(Number(age) < Number(minAge)); // trueTo compare human-readable text, use localeCompare. It respects case and accents in the user's language:
console.log("apple".localeCompare("Zebra")); // negative: "apple" comes first
console.log(["b", "A", "a", "B"].sort((x, y) => x.localeCompare(y)));
// [ 'a', 'A', 'b', 'B' ]The exact order of "a" and "A" depends on the locale, but the case-insensitive grouping is consistent.
null, undefined, and NaN in Relations
Relational operators convert null to 0 and undefined to NaN. Equality does not convert either of them. This mismatch produces results that look contradictory:
console.log(null > 0); // false
console.log(null == 0); // false
console.log(null >= 0); // true: 0 >= 0
console.log(undefined < 1); // false
console.log(undefined > 1); // false
console.log(undefined == 0); // false
console.log(NaN < 1, NaN > 1, NaN === NaN); // false false falseThe undefined and NaN behavior has a practical consequence. Look at the negated condition !(x < limit). You might expect it to mean the same as x >= limit, but if x is undefined the first form is true and the second is false. When a value might be missing, check for that first:
function isOverLimit(x, limit) {
if (x == null || Number.isNaN(x)) return false;
return x > limit;
}
console.log(isOverLimit(undefined, 5)); // false
console.log(isOverLimit(7, 5)); // trueComparing Dates
Dates convert to their timestamp with relational operators, so < and > work as expected. Equality, though, compares references, as shown earlier.
const start = new Date(2026, 0, 1);
const end = new Date(2026, 5, 1);
console.log(start < end); // true
console.log(start <= new Date(2026, 0, 1)); // true
console.log(start == new Date(2026, 0, 1)); // false: different objectsChoosing an Operator
| Situation | Use |
|---|---|
| Default equality check | `===` and `!==` |
| Value is `null` or `undefined` | `x == null` if allowed, or both `===` checks |
| Testing for `NaN` | `Number.isNaN(x)` |
| Same object? | `===` |
| Same contents? | Compare fields, timestamps, or elements yourself |
| Ordering numbers from strings | Convert with `Number()` first, then `<` or `>` |
| Ordering human text | `a.localeCompare(b)` |
The switch statement, covered later in this tutorial, always uses strict equality to match cases. That is one more reason to get used to thinking in ===.
Exercises
Exercise
Predict the output of each line: console.log("5" == 5), console.log("5" === 5), console.log(false == ""), console.log(null == false).
Show answer
true, false, true, false. "5" converts to 5 under ==. === sees different types. false becomes 0 and "" becomes 0. null is only loosely equal to null and undefined, so null == false is false even though both are falsy.
Exercise
An array of prices read from a CSV is ["100", "25", "9"]. Calling prices.sort((a, b) => (a < b ? -1 : 1)) gives ["100", "25", "9"]. Why, and how do you fix it?
Show answer
Both operands are strings, so < compares them character by character: "1" < "2" < "9". Convert to numbers first: prices.map(Number).sort((a, b) => a - b) gives [9, 25, 100].
Exercise
Why does null >= 0 return true while null == 0 and null > 0 both return false?
Show answer
Relational operators convert null to the number 0, so null >= 0 becomes 0 >= 0 (true) and null > 0 becomes 0 > 0 (false). Loose equality does not convert null to a number. It treats null as equal only to null and undefined, so null == 0 is false.
Exercise
Write a function sameDay(a, b) that returns true when two Date objects represent the same instant, and explain why a === b is not enough.
Show answer
const sameDay = (a, b) => a.getTime() === b.getTime(); Using a === b compares object references, so two separately created Date objects with the same time are not strictly equal. getTime() returns numbers, which === compares by value.