Comparison
A comparison answers a yes-or-no question: is the order total over a hundred dollars, does the password match, is the user 18 yet. The result of a comparison is always a boolean, true or false.
Comparison operators
The simplest comparison is "greater than":
console.log(5 > 3); // true| Operator | Meaning | Example | Result |
|---|---|---|---|
> | greater than | 5 > 3 | true |
< | less than | 5 < 3 | false |
>= | greater than or equal | 5 >= 5 | true |
<= | less than or equal | 4 <= 3 | false |
=== | equal | 5 === 5 | true |
!== | not equal | 5 !== 3 | true |
Strict equality
The === operator checks that the values match and have the same type. So the number 5 and the string '5' are not equal:
console.log(5 === '5'); // falseNote that equality is written with three = signs. A single = is assignment, not comparison.
Loose equality
JavaScript also has the old == operator. Before comparing, it converts the values to one type, which gives surprising results:
console.log('5' == 5); // true
console.log(0 == ''); // trueBecause of such surprises, modern code uses only === and !==. The == and != pair shows up mostly in old programs.
Storing the result
A comparison is an ordinary expression, and its result can go into a variable. Such variables are usually named starting with is or has:
const age = 20;
const isAdult = age >= 18;
console.log(isAdult); // trueSuch a variable is then used in conditions — that is the next chapter.
Comparing strings
Strings are compared character by character, alphabetically: a letter further along in the alphabet counts as "greater". Capital letters are less than lowercase ones:
console.log('cat' > 'car'); // true
console.log('Anna' === 'anna'); // falseTo compare strings ignoring case, bring both to the same case: a.toLowerCase() === b.toLowerCase().
NaN equals nothing
The special value NaN is not equal to anything, not even itself. So the check x === NaN is always false:
console.log(NaN === NaN); // false
console.log(Number.isNaN(NaN)); // trueTo check for NaN, use the Number.isNaN() function.
Common mistake
Numbers written as strings are compared as text — by the first character, not by size. The character '1' is less than '9', so '10' turns out to be less than '9':
console.log('10' < '9'); // true
console.log(Number('10') < Number('9')); // falseValues from forms and files arrive as strings, so convert them to numbers before comparing.