Comparison Operators
Compare values to get a true or false result.
Syntax
a === b
a !== b
a > bComparison operators compare two values and return a Boolean.
| Operator | Meaning |
|---|---|
== | Equal (loose) |
=== | Equal value and type (strict) |
!= | Not equal (loose) |
!== | Not equal value or type |
> < >= <= | Greater / less than |
Example
Loading editorβ¦
Press Run to execute the code.
When to use it
- Check whether a user's age meets the minimum requirement before granting access to content.
- Compare a form's password and confirm-password fields for equality before submission.
- Validate that a entered discount code matches the expected string using strict equality.
More examples
Strict vs loose equality
Contrasts == (loose, coerces types) with === (strict, no coercion) to show why === is preferred.
console.log(5 == "5"); // true β loose: coerces types
console.log(5 === "5"); // false β strict: no coercion
console.log(0 == false); // true
console.log(0 === false);// falseRelational comparisons
Uses >= to compare a user's age against a minimum, branching to allow or deny access.
const userAge = 17;
const MIN_AGE = 18;
if (userAge >= MIN_AGE) {
console.log("Access granted");
} else {
console.log("Access denied β must be 18+");
}Password confirmation check
Uses strict equality to verify that a password and its confirmation field contain the same string.
const password = "S3cr3t!";
const confirm = "S3cr3t!";
const match = password === confirm;
console.log("Passwords match:", match); // true
Discussion