Comparison Operators
Overview
Comparison operators are used in logical statements to determine equality or difference between variables or values. They return a boolean value (true or false).
These operators form the absolute backbone of application logic. Every if statement, while loop, and ternary operator relies on comparisons to make decisions.
JavaScript has two types of equality: Loose Equality (==) which coerces types, and Strict Equality (===) which checks both value AND data type.
Syntax
let age = 18;
console.log(age === 18); // true (Value and type match)
console.log(age === '18'); // false (Types are different: number vs string)
console.log(age !== 20); // true (18 is not strictly equal to 20)let age = 18;
// JavaScript coerces the string '18' into a number before comparing!
console.log(age == '18'); // true
console.log(0 == false); // true (0 is falsy)
console.log('' == false); // true (Empty string is falsy)console.log(10 > 5); // true (Greater than)
console.log(10 < 5); // false (Less than)
console.log(10 >= 10); // true (Greater than or equal to)
console.log(10 <= 9); // false (Less than or equal to)Common Pitfalls
- Using loose equality (
==) can lead to bizarre bugs due to JavaScript's complex type coercion rules (e.g.,[] == falseis true, but[] == trueis false). Professional codebases enforce strict equality (===) using ESLint.
Interview Questions
== and === in JavaScript?== (loose equality) converts the operands to the same type before making the comparison. === (strict equality) does not convert types; if the types are different, it immediately returns false.
Object.is(NaN, NaN) return compared to NaN === NaN?NaN === NaN is strangely false in JS. However, Object.is(NaN, NaN) correctly returns true. Object.is is useful for checking exact same values without the weird quirks of ===.
Real-World Example
Checking if a user meets the age requirements to access a restricted page.
const userAge = parseInt(inputElement.value);
if (userAge >= 18) {
grantAccess();
} else {
showError("You must be 18 or older.");
}Check Your Knowledge
Test your understanding of Comparison Operators with these quick questions.