Comparison Operators
Comparison operators evaluate two values and return a boolean —
either true or false.
The critical distinction between == (loose) and
=== (strict) equality is one of JavaScript's most important
concepts, and getting it wrong leads to some of the sneakiest bugs in any codebase.
Comparison Operator Overview
JavaScript provides six comparison operators. Every one of them
returns a boolean value — true or
false. They are the building blocks of all
conditional logic: if statements, ternary
expressions, and loop conditions all rely on comparisons.
| Operator | Name | Example | Result |
|---|---|---|---|
| == | Loose equality | 5 == "5" |
true |
| === | Strict equality | 5 === "5" |
false |
| != | Loose inequality | 5 != "5" |
false |
| !== | Strict inequality | 5 !== "5" |
true |
| < | Less than | 3 < 5 |
true |
| > | Greater than | 3 > 5 |
false |
| <= | Less than or equal | 5 <= 5 |
true |
| >= | Greater than or equal | 6 >= 5 |
true |
Loose (==) vs Strict (===) Equality
This is the most important distinction in JavaScript comparisons.
The loose equality operator ==
attempts to coerce both operands to the same type before comparing.
The strict equality operator ===
compares both value and type — no coercion, no surprises.
// ── Loose equality (==) — performs type coercion ─────────────
5 == "5"; // true — string "5" is coerced to number 5
0 == false; // true — false coerces to 0
0 == ""; // true — "" coerces to 0
null == undefined; // true — special rule: only these two are == each other
[] == false; // true — [] → "" → 0, false → 0
// ── Strict equality (===) — no coercion ──────────────────────
5 === "5"; // false — number ≠ string type
0 === false; // false — number ≠ boolean type
null === undefined;// false — different types
5 === 5; // true — same value, same type ✓
"hello" === "hello"; // true — same value, same type ✓
true === true; // true — same value, same type ✓
// ── Objects: compared by reference, not value ────────────────
const a = { x: 1 };
const b = { x: 1 };
a === b; // false — different objects in memory
const c = a;
a === c; // true — same reference=== and !== in production JavaScript.
Loose equality (==) has over 50 coercion rules — memorising them all is
impractical and error-prone. The only valid use case for == is
value == null as a shorthand to check both null and
undefined at once.
Relational Operators
Relational operators compare the magnitude or order of two values. With numbers they work intuitively — but with strings, comparisons are done lexicographically (character by character using Unicode code points), which can produce surprising results when mixing types.
// ── Numbers (intuitive) ──────────────────────────────────────
5 < 10; // true
10 > 5; // true
5 <= 5; // true (equal counts!)
5 >= 6; // false
// ── Strings (lexicographic / Unicode order) ──────────────────
"apple" < "banana"; // true — "a" (97) comes before "b" (98)
"Z" < "a"; // true — uppercase letters have lower code points!
"10" < "9"; // true — "1" (49) < "9" (57), NOT numeric comparison
// ── Mixed types — string gets coerced to number ──────────────
"5" > 3; // true — "5" → 5, then 5 > 3
"10" > 9; // true — "10" → 10, then 10 > 9
// ── Practical: age gate ───────────────────────────────────────
const age = 20;
if (age >= 18) {
console.log("Access granted");
}
// ── Sorting numbers correctly requires a comparator ──────────
[10, 9, 2, 100].sort((a, b) => a - b); // [2, 9, 10, 100]
[10, 9, 2, 100].sort(); // [10, 100, 2, 9] ← string sort (wrong!)
"10" < "9" is true because "1"
comes before "9" in Unicode. Always convert to numbers before numeric comparison:
Number("10") < Number("9") → false.
Type Coercion in Comparisons
When operands have different types, JavaScript
follows a conversion algorithm before comparing. Understanding these rules helps you
predict outcomes — and avoid them by using ===.
| Expression | What JS does | Result |
|---|---|---|
| 5 == "5" | Converts "5" → 5, then compares 5 == 5 | true |
| false == 0 | Converts false → 0, then compares 0 == 0 | true |
| true == 1 | Converts true → 1, then compares 1 == 1 | true |
| null == undefined | Special rule — only these two are == each other | true |
| null == 0 | null only == undefined; no other coercion | false |
| NaN == NaN | NaN is not equal to anything, including itself | false |
| [] == false | [] → "" → 0, false → 0, then 0 == 0 | true |
| "" == false | Converts false → 0 and "" → 0 | true |
// ── Coercion algorithm summary ────────────────────────────────
// 1. If types match, compare directly
// 2. null == undefined only (special rule)
// 3. number vs string → convert string to number
// 4. boolean → convert to number (true=1, false=0)
// 5. object vs primitive → call .valueOf() / .toString()
// ── The NaN trap ─────────────────────────────────────────────
NaN == NaN; // false — NaN ≠ NaN (this is by design!)
NaN === NaN; // false — strict makes no difference
// ✅ Correct ways to check for NaN
Number.isNaN(NaN); // true — preferred
isNaN("hello"); // true — careful: coerces first ("hello"→NaN)
Number.isNaN("hello"); // false — does NOT coerce (better!)
// ── null vs undefined ─────────────────────────────────────────
null == undefined; // true — the only == pair with null
null === undefined; // false — strict, different types
null == 0; // false — null only == undefined
null == false; // false — same rule
// ✅ Safe null/undefined check with == (the one valid use)
function greet(name) {
if (name == null) { // catches both null AND undefined
return "Hello, Guest!";
}
return `Hello, ${name}!`;
}Comparing Objects & References
In JavaScript, objects (including arrays and functions) are compared by reference, not by their contents. Two objects with identical properties are not equal unless they point to the same location in memory.
// ── Object comparison — by reference ─────────────────────────
const a = { name: "Alice" };
const b = { name: "Alice" };
a === b; // false — different objects in memory
const c = a; // c now points to the SAME object as a
a === c; // true — same reference
// ── Arrays work the same way ─────────────────────────────────
[1, 2, 3] === [1, 2, 3]; // false — different array objects
const arr1 = [1, 2, 3];
const arr2 = arr1;
arr1 === arr2; // true — same reference
// ── Deep equality: compare contents ──────────────────────────
JSON.stringify(a) === JSON.stringify(b); // true — compare serialized form
// ⚠ Caveat: fails for undefined, functions, circular refs
// ── Primitive wrappers (avoid!) ──────────────────────────────
new Number(5) === new Number(5); // false — two different objects
new Number(5) == 5; // true — coerces via valueOf()
structuredClone() + ===,
or a utility like _.isEqual() from Lodash. JSON.stringify()
works for simple cases but ignores undefined, functions, and Symbol
keys.
Try It — Live Editor
Experiment with JavaScript comparison operators below.
Modify values, switch between == and
===, and observe coercion live — all without leaving this
page.
Common Patterns & Recipes
These comparison patterns appear constantly in real JavaScript projects. Master them to write clean, predictable, bug-free comparisons.
// ── Null/undefined check (the one good use of ==) ────────────
function process(value) {
if (value == null) return; // catches null AND undefined
console.log(value);
}
// ── Range check ──────────────────────────────────────────────
const score = 75;
const isPassing = score >= 60 && score <= 100; // true
// ── Clamp (keep value within bounds) ─────────────────────────
const clamp = (n, min, max) => Math.min(Math.max(n, min), max);
clamp(150, 0, 100); // 100
// ── Safe NaN check ───────────────────────────────────────────
const safeNum = n => Number.isNaN(n) ? 0 : n;
safeNum(NaN); // 0
safeNum(42); // 42
// ── Type-safe equality helper ────────────────────────────────
const eq = (a, b) => a === b; // always use === inside utilities too
eq(5, "5"); // false
eq(5, 5); // true
// ── String comparison for sorting ────────────────────────────
const names = ["Charlie", "alice", "Bob"];
names.sort((a, b) => a.localeCompare(b)); // ["alice", "Bob", "Charlie"]
// ── Deep object compare (simple) ─────────────────────────────
const deepEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);
deepEqual({ x: 1 }, { x: 1 }); // true
deepEqual([1, 2], [1, 2]); // true
5 == "5" evaluate to in JavaScript?NaN === NaN return?- JavaScript has six comparison operators:
==,===,!=,!==,<,>,<=,>=. All return a boolean. - The loose equality operator
==coerces types before comparing. This leads to many counterintuitive results like0 == false → trueand[] == false → true. - The strict equality operator
===compares both value and type without any coercion — always prefer it. Use!==for strict inequality. - The only recommended use of
==isvalue == null, which checks for bothnullandundefinedin a single expression. - NaN is never equal to itself:
NaN === NaNisfalse. UseNumber.isNaN(value)to check for NaN safely. - Relational operators (
<,>,<=,>=) work numerically on numbers but lexicographically on strings — always convert to numbers for numeric comparison. - Objects and arrays are compared by reference, not by contents. Two object literals with identical properties are not equal unless they point to the same object in memory.
- For deep equality of objects, use
JSON.stringify(a) === JSON.stringify(b)for simple cases, or a library like Lodash's_.isEqual()for production use.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.