Comparison operators
Every "if this happens, do that" starts with a comparison. Here you build the yes/no questions that will later make decisions for you.
They compare two values and always return a boolean (true or false).
| Operator | Meaning | Example | Result |
|---|---|---|---|
=== |
Strictly equal | 3 === 3 |
true |
!== |
Strictly different | 3 !== 4 |
true |
< |
Less than | 3 < 4 |
true |
> |
Greater than | 3 > 4 |
false |
<= |
Less than or equal | 3 <= 3 |
true |
>= |
Greater than or equal | 4 >= 5 |
false |
Remember:
=assigns a value, whereas===compares. Confusing them is one of the most typical mistakes when starting out.
Logical operators
They are used to combine several conditions.
&&(AND):trueonly if both sides are true.||(OR):trueif at least one is true.!(NOT): inverts the value:!trueisfalse.
const age = 20;
const hasTicket = true;
console.log(age >= 18 && hasTicket); // true: meets both
console.log(age < 18 || hasTicket); // true: meets one
console.log(!hasTicket); // false
Analogy
Imagine entry to a concert:
- With
&&you need to be of legal age AND have a ticket. Fail either one and you don't get in. - With
||they let you in if you are VIP OR you have an invitation. One is enough.
You can now compare with confidence... as long as the types match. In the next lesson coercion enters the scene, and that's where JavaScript gets mischievous. Hold on tight.
Examples
Comparisons return booleans
const grade = 7;
console.log("passes:", grade >= 5);
console.log("outstanding:", grade >= 9);
Combine conditions
const age = 20;
const license = true;
const canDrive = age >= 18 && license;
console.log("can drive:", canDrive);