Comparison operators
Learn to compare values with ==, ===, !=, <, >, <= and >=.
Comparison operators
Comparison operators put two values side by side and return true or false based on their relationship. <, >, <=, >= check ordering; == and != check equality.
The result is a boolean. So you can assign a comparison to a variable: const canDrive = age >= 18;. canDrive now holds true or false.
Loose and strict equality
JavaScript has two forms of equality. == is loose equality: when types differ, it converts first and then compares. That is why "5" == 5 returns true.
=== is strict equality: it checks both value and type. "5" === 5 returns false because one is a string, the other a number. In everyday code, prefer === and !==; they avoid surprises.
Exercise Driving age check
Declare age with the value 18. Then declare a canDrive variable and assign it the result of age >= 18.
Show example solution
// Declare age and canDrive
let age = 18;
let canDrive = age >= 18;
Test yourself
-
What is the result of "5" == 5?
console.log("5" == 5);- false
- TypeError
- true
- NaN
Show answer
true — Correct. == does type conversion; the string "5" equals the number 5.
-
Write the age condition
const age = 20; const canVote = age ____ 18; console.log(canVote);Show answer
const age = 20; const canVote = age >= 18; console.log(canVote); -
Match the comparison operator
- ==
- Equal (loose)
- ===
- Strict equal
- <
- Less than
- >=
- Greater or equal