JavaScript Roadmap — Day 9: Comparison Operators

 

JavaScript · Day 9 of 180 · Beginner Phase

Comparison Operators

Comparison operators are behind every decision in JavaScript — login checks, age verification, price comparisons. Master them completely and eliminate an entire category of bugs forever.

Day 9 / 180
Beginner Phase

Think about what happens every second inside a running app:

🔐 Login check: enteredPassword === savedPassword
🎂 Age verification: age >= 18
💰 Discount eligible: totalBill > 1000
📦 Stock available: stock !== 0

Every comparison returns exactly one of two things — true or false. These booleans then drive if statements, loops, and every decision in your program. Comparison operators are the foundation of all logic in JavaScript.

But there is one massive trap — the difference between == and ===. This single distinction has caused thousands of developers to spend hours hunting bugs they did not understand. Today we fix that permanently.

1. All Comparison Operators — Full Chart

JavaScript has 8 comparison operators. Every single one returns true or false:

Operator Name Example Result
== Loose equality "5" == 5 true ⚠️
=== Strict equality "5" === 5 false ✅
!= Loose not equal "5" != 5 false ⚠️
!== Strict not equal "5" !== 5 true ✅
> Greater than 10 > 5 true
< Less than 10 < 5 false
>= Greater or equal 10 >= 10 true
<= Less or equal 5 <= 10 true

2. == vs === — The Most Important Difference 🔥

Both check equality — but in completely different ways. This is the most misunderstood concept for JavaScript beginners:

== Loose Equality — CONVERTS TYPE FIRST ⚠️
Converts both values to the same type before comparing. That is why "5" == 5 is true — the string "5" gets converted to the number 5 first.
=== Strict Equality — NO TYPE CONVERSION ✅
Both value and type must be identical. No conversion happens. "5" === 5 is false because one is a string and the other is a number.
JavaScript — == vs === Complete Examples
// == converts type before comparing
console.log("5"   ==  5);       // true  ← "5" becomes 5
console.log(0    ==  false);   // true  ← false becomes 0
console.log(""   ==  false);   // true  ← "" → 0, false → 0
console.log(null ==  undefined); // true  ← special rule
console.log([]   ==  false);   // true  ← [] → "" → 0

// === never converts — value AND type must match
console.log("5"   === 5);       // false ← string !== number ✅
console.log(0    === false);   // false ← number !== boolean ✅
console.log(""   === false);   // false ← string !== boolean ✅
console.log(null === undefined); // false ← different types ✅
console.log(5    === 5);       // true  ← same value, same type ✅

// Real world — login check
const savedPassword = "waheed123";
const entered       = "waheed123";
console.log(entered === savedPassword); // true ✅ always use ===

🔥 Golden Rule — memorize this: Always use === in production code. The only acceptable use of == is value == null which conveniently catches both null and undefined at once. Everywhere else — strict equality only.

3. != and !== — Not Equal Operators

The same loose vs strict rule applies here. != converts types before comparing. !== does not. Always use !==:

JavaScript — != vs !==
// != loose — converts type first
console.log("5" !=  5);    // false ← "5" == 5 so != is false
console.log(0   !=  false);  // false ← 0 == false
console.log(1   !=  true);   // false ← 1 == true

// !== strict — checks type too
console.log("5" !== 5);    // true  ← different types ✅
console.log(0   !== false);  // true  ← different types ✅
console.log(5   !== 5);    // false ← same value, same type

// Real world — stock availability check
let stock = 0;
if(stock !== 0) {
  console.log("Item available — add to cart");
} else {
  console.log("Out of stock!"); // this runs
}

4. >, <, >=, <= — Size Comparisons

These operators compare numbers — and strings alphabetically. They are straightforward but have a few surprises worth knowing:

JavaScript — Greater and Less Than
// Basic number comparisons
console.log(10 >  5);    // true
console.log(10 <  5);    // false
console.log(10 >= 10);   // true  ← equal is included
console.log(10 <= 9);    // false

// Real world use cases
let age    = 17;
let salary = 85000;
let score  = 75;

console.log(age    >= 18);    // false — minor
console.log(salary >  50000); // true  — good salary
console.log(score  >= 50);    // true  — passing grade
console.log(score  <  40);    // false — not failing

// Range check — between two values
let temp = 35;
let isHot = temp > 30 && temp <= 45;
console.log(isHot); // true — typical Pakistan summer 😄

// Comparing mixed types — JS converts to number
console.log("10" > 5);    // true  ← "10" converts to 10
console.log(null  > 0);    // false ← null converts to 0
console.log(null  >= 0);   // true  ← null converts to 0
Pro Tip #1 — >= includes the boundary
A very common bug — writing age > 18 when you mean age >= 18. The > operator is strictly greater than — an 18-year-old fails the check. Always ask yourself: does the boundary value count or not?
Pro Tip #2 — String comparison is case sensitive
Uppercase letters are "smaller" than lowercase in Unicode — A (65) comes before z (122). So "Z" < "a" is true. When comparing user input always normalize first with .toLowerCase() or .toUpperCase().
Pro Tip #3 — NaN is never equal to anything
NaN === NaN is false — NaN is not equal even to itself. This is unique JavaScript behavior. Always use Number.isNaN(value) to check for NaN — never === NaN.

5. String Comparison — Unicode Rules 🔥

When comparing strings JavaScript goes character by character using Unicode values. Understanding this prevents a very common category of bugs in form validation and sorting:

JavaScript — String Comparison Deep Dive
// Alphabetical comparison — character by character
console.log("apple"  < "banana");  // true  ← a < b
console.log("cat"    > "car");     // true  ← t > r (3rd char)
console.log("abc"    === "abc");   // true  ← exact match

// TRAP — uppercase vs lowercase
console.log("Z" < "a");             // true! — Z(90) < a(97)
console.log("Waheed" === "waheed");  // false — W !== w

// Fix — normalize case before comparing
const input = "WAHEED";
const saved = "waheed";
console.log(input.toLowerCase() === saved); // true ✅

// TRAP — number strings compare as strings!
console.log("10" > "9");   // false! "1" < "9" alphabetically
console.log(10  > 9);    // true  ← number comparison ✅

// Fix — always convert to Number first
console.log(Number("10") > Number("9")); // true ✅

6. Reference vs Value — The Permanent Confusion 🔥

This is where almost every beginner gets permanently confused. When comparing objects and arrays JavaScript does not compare the contents — it compares the memory address (reference). Two objects with identical contents are still not equal:

JavaScript — Reference vs Value Comparison
// Primitives — VALUE is compared
console.log(5       === 5);       // true  ✅
console.log("hello" === "hello"); // true  ✅
console.log(true    === true);    // true  ✅

// Objects — REFERENCE (memory address) is compared
const obj1 = { name: "Waheed" };
const obj2 = { name: "Waheed" }; // identical content
const obj3 = obj1;              // same reference!

console.log(obj1 === obj2); // false ← different memory locations
console.log(obj1 === obj3); // true  ← same memory location ✅

// Arrays follow the same rule
const arr1 = [1, 2, 3];
const arr2 = [1, 2, 3];
console.log(arr1 === arr2); // false ← different arrays

// How to compare objects correctly
const user1 = { name: "Waheed", age: 22 };
const user2 = { name: "Waheed", age: 22 };

// Option 1 — compare property by property
const isSame = user1.name === user2.name && user1.age === user2.age;
console.log(isSame); // true ✅

// Option 2 — JSON.stringify (for simple objects)
console.log(JSON.stringify(user1) === JSON.stringify(user2)); // true ✅

💡 Simple rule to remember: Primitives (number, string, boolean) are compared by VALUE. Objects and arrays are compared by REFERENCE — their memory address. Two separate objects with identical content are still not equal in JavaScript's eyes.

7. Try It Yourself

Predict every output before clicking Run Code — then check how many you got right!

✏️ Try it Yourself — Comparison Operators
OUTPUT
// Click Run Code to see output
💡 Edit the code and click Run!

8. Practice Tasks

Task 1 — Easy: Predict The Output

Before running — write your predicted output as comments next to each line. Then run and score yourself: 5 == "5", 5 === "5", null == false, null === false, NaN === NaN, 0 == "", [] == false. How many did you get right?

Task 2 — Medium: Login System

Build a login check. Set savedUsername = "waheed" and savedPassword = "pakistan123". User input can be any case. Use strict equality and normalize the username to lowercase before comparing. If both match print "Login successful!" otherwise print "Wrong credentials!".

Task 3 — Hard: Grade Calculator

Create a marks variable (0-100). Use comparison operators to calculate the grade: 90+ = A+, 80-89 = A, 70-79 = B, 60-69 = C, 50-59 = D, below 50 = F. Also validate that marks are in a valid range (marks >= 0 && marks <= 100). Print "Invalid marks!" for out of range values.

Next Lesson
Day 10 — Logical Operators
View Full Roadmap →
Enjoying this roadmap?
Follow Muhammad Waheed Asghar for daily JavaScript tips and updates!