Tutorials JavaScript Comparison Operators
Ch 9 / 78
Chapter 14 Beginner 6 min read JavaScript

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.

What you'll learn
The 6 comparison operators and their purpose
Loose equality (==) with type coercion rules
Strict equality (===) — no coercion, always use this
Relational operators: <, >, <=, >=
Comparing strings, null, undefined, and NaN
Common comparison pitfalls and how to avoid them

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.

Loose Equality
== and != — compares after type coercion. Often surprising.
Strict Equality
=== and !== — no coercion. The recommended choice always.
Relational
<, >, <=, >= — compare order or magnitude.
Special Cases
NaN, null, undefined — behave unlike any other value.
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 — converts type first
5 == "5" true
0 == false true
0 == "" true
null == undefined true
[] == false true
null == 0 false
===
Strict — value AND type must match
5 === "5" false
0 === false false
0 === "" false
null === undefined false
5 === 5 true
"hi" === "hi" true
JavaScript — == vs ===
// ── 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
Rule of Thumb
Always use === 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.

<
Less Than
Returns true if the left operand is strictly less than the right.
5 < 10 → true
>
Greater Than
Returns true if the left operand is strictly greater than the right.
10 > 5 → true
<=
Less Than or Equal
Returns true if the left operand is less than or equal to the right.
5 <= 5 → true
>=
Greater Than or Equal
Returns true if the left operand is greater than or equal to the right.
6 >= 5 → true
JavaScript — Relational Operators
// ── 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!)
String Sort Gotcha
When comparing two strings, JavaScript compares Unicode code points, not numeric values. "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
JavaScript — Type Coercion in Practice
// ── 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.

{ }
Plain Objects
Two object literals with identical contents are never == or ===.
{} === {} → false
[ ]
Arrays
Arrays are objects — same rule applies. Identical arrays are not equal.
[] === [] → false
ref
Same Reference
When a variable is assigned to another variable, both point to the same object.
a = b; a === b → true
JSON
Deep Equality
To compare object contents, serialize to JSON or use a utility like Lodash.
JSON.stringify(a) === JSON.stringify(b)
JavaScript — Object & Reference Comparisons
// ── 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()
Deep Equality Libraries
For complex object comparison, use 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.

Live Editor
✎ Editor
👁 Preview

Common Patterns & Recipes

These comparison patterns appear constantly in real JavaScript projects. Master them to write clean, predictable, bug-free comparisons.

JavaScript — Comparison Recipes
// ── 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
⚡
Free Resource
Download our JavaScript Cheat Sheet
All operators, comparison rules & coercion tables — one printable page.
Get Sheet
Quick Check
What does 5 == "5" evaluate to in JavaScript?
Quick Check
What does NaN === NaN return?
Quick Check
Which operator should you always prefer for equality checks?
Chapter Summary
  • JavaScript has six comparison operators: ==, ===, !=, !==, <, >, <=, >=. All return a boolean.
  • The loose equality operator == coerces types before comparing. This leads to many counterintuitive results like 0 == false → true and [] == 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 == is value == null, which checks for both null and undefined in a single expression.
  • NaN is never equal to itself: NaN === NaN is false. Use Number.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

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel