Now for something new. Comparison operators compare two values and give you back a boolean: true or false.
| Operator | Meaning | Example | Result |
|---|---|---|---|
> | greater than | 10 > 5 | true |
< | less than | 10 < 5 | false |
>= | greater than or equal to | 5 >= 5 | true |
<= | less than or equal to | 4 <= 3 | false |
=== | equal to | 5 === 5 | true |
!== | not equal to | 5 !== 5 | false |
const myAge = 15;
const votingAge = 18;
console.log(myAge >= votingAge);
console.log(myAge < votingAge);
console.log(myAge === 15);
console.log(myAge !== 15);
It prints
false true true false
These are the questions your program will ask before it makes decisions. "Is the user old enough?" "Is the password correct?" "Has the player run out of lives?" Each question gives a true or false answer, and in Grade 4, your program will act on that answer.
If you always forget which way round < and > go, imagine the symbol is a hungry alligator's mouth. The alligator always wants to eat the bigger number. In 10 > 5, the mouth opens toward 10. 🐊
Comparing strings
You can compare strings too. JavaScript compares them alphabetically, character by character, a bit like a dictionary:
console.log("apple" < "banana");
console.log("cat" > "car");
console.log("Zebra" < "apple");
console.log("10" < "9");
It prints
true true true true
The first two make sense: "apple" comes before "banana" in the dictionary, and "cat" comes after "car" (because "t" comes after "r").
The last two are surprising:
- Capital letters come before lowercase letters. Every uppercase letter is "less than" every lowercase letter, so
"Zebra" < "apple". - Numbers in strings are compared as text, not as numbers.
"10"starts with"1", which comes before"9", so"10" < "9". If you want to compare numbers, make sure they're actual numbers, not strings!