Comparison Operators
Comparison operators ask a question about two values and always answer with true or false.
Greater than, less than and their or-equal forms, plus the equality operators. Comparing strings uses character codes, so uppercase sorts before lowercase and 10 is less than 9 as text.
EXERCISE
1Asking Questions About Two Values
Every comparison produces a boolean, which is what makes them the fuel for every decision your program makes.
The four size comparisons:
console.log(10 > 5); // true
console.log(10 < 5); // false
console.log(10 >= 10); // true greater than OR equal
console.log(10 <= 9); // false
// The answer is always a boolean:
console.log(typeof (10 > 5)); // boolean
Which is why they feed straight into decisions:
const age = 20;
const price = 1200;
if (age >= 18) {
console.log("Can vote"); // this runs
}
const needsDelivery = price < 500;
console.log(needsDelivery); // false
const items = [1, 2, 3];
console.log(items.length > 0); // true
Chaining does not work the way it does in maths:
const x = 5;
// You might write this, meaning "between 1 and 10":
console.log(1 < x < 10); // true
// But it is doing something else entirely:
// 1 < 5 -> true
// true < 10 -> true converts to 1, and 1 < 10 is true
// It returned the right answer by luck. Try it the other way:
console.log(20 < x < 10); // true <- clearly wrong
// Say it properly, with two comparisons joined:
console.log(x > 1 && x < 10); // true
console.log(20 < x && x < 10); // false
That chaining example is worth remembering because it does not throw an error, it just quietly returns a wrong answer that happens to be right often enough to hide the bug. Any time you want a range, write two separate comparisons and join them with &&.
EXERCISE
2Comparing Text Instead of Numbers
Strings can be compared with the same operators, but they are compared character by character rather than by their meaning.
When both sides are strings, compares character codes, left to right, like dictionary order with a twist.
Basic alphabetical behaviour:
console.log("apple" < "banana"); // true
console.log("cat" > "car"); // true t comes after r
console.log("abc" === "abc"); // true
The twist: uppercase sorts before lowercase:
console.log("Zebra" < "apple"); // true !
// Every uppercase letter has a lower code than every lowercase one.
// Z is 90. a is 97.
// So sorting names naively separates them by case:
const names = ["ada", "Grace", "alan", "Bob"];
console.log([...names].sort());
// [ 'Bob', 'Grace', 'ada', 'alan' ]
// Compare case-insensitively when you mean alphabetical:
console.log([...names].sort((a, b) => a.localeCompare(b)));
// [ 'ada', 'alan', 'Bob', 'Grace' ]
And numbers stored as text compare as text:
console.log("10" < "9"); // true <- "1" is before "9"
console.log(10 < 9); // false numbers compare properly
// Mixed types convert to number, which is usually what you wanted:
console.log("10" < 9); // false
console.log("10" > 9); // true
The "10" < "9" result is a real bug that ships regularly, usually when numbers come out of an input box or a URL and nobody converted them. If you are sorting or comparing quantities, prices or dates, make sure both sides are actually numbers first. The comparison will not warn you.
EXERCISE
3Comparisons That Return False for Everything
A handful of values behave strangely under comparison, and knowing which ones saves you from a genuinely confusing hour.
NaN is not equal to anything, including itself:
console.log(NaN === NaN); // false
console.log(NaN > 0); // false
console.log(NaN < 0); // false
console.log(NaN === 0); // false
// All four false. So this check never works:
const result = "abc" * 2; // NaN
if (result === NaN) {
console.log("never runs");
}
// Use the built-in check instead:
console.log(Number.isNaN(result)); // true
undefined refuses to compare by size:
console.log(undefined > 0); // false
console.log(undefined < 0); // false
console.log(undefined === 0); // false
// null is different, and inconsistent:
console.log(null > 0); // false
console.log(null === 0); // false
console.log(null >= 0); // true <- !
// null converts to 0 for < and >, but not for ===.
// There is no good reason. It is simply how it is.
Objects compare by identity, not by contents:
console.log({ a: 1 } === { a: 1 }); // false two different objects
console.log([1, 2] === [1, 2]); // false
const x = { a: 1 };
const y = x;
console.log(x === y); // true same object, two names
// To compare contents you must compare the parts:
const p = {
a: 1 }, q = { a: 1
};
console.log(p.a === q.a); // true
Pro Tip: Two rules cover almost all of this. Never compare against
NaNwith an operator, useNumber.isNaN. And never expect===to tell you whether two objects hold the same data, because it only tells you whether they are the same object. Both catch people exactly once, and then never again.
