Chapter IV · Operators & Expressions

Comparison Operators

Comparison operators (<, >, <=, >=) test the relative order of two values and always produce a boolean — true or false.

01 What Are Comparison Operators?

These operators exist to make decisions: is this cart total over the free-shipping threshold, is this user old enough, is this timestamp before that one? The result is always a boolean, which is exactly what an if statement or loop condition needs.

02 Simple Example

Comparing numbers and strings.

comparison.js
console.log(10 > 5);   // true
console.log(10 <= 10); // true
console.log('apple' < 'banana'); // true — alphabetical (lexicographic) order

03 How It Works

Numbers compare by value. Strings compare lexicographically — character by character, by Unicode code point, the same idea as alphabetical order in a dictionary but strict about case (uppercase letters sort before lowercase). If the operands are different types, JavaScript coerces one side to a number before comparing — which is exactly where surprises creep in.

04 Production Example

Gating free shipping and validating an age requirement.

shipping.js
function qualifiesForFreeShipping(cartTotal) {
  return cartTotal >= 50;
}

function isEligibleForSignup(userAge) {
  return userAge >= 13;
}

05 Mental Model

"A number line judge: it only ever answers true or false about where two things sit relative to each other."

06 Common Mistakes

  • '10' < '9' is true — string comparison is character by character, not numeric, so '1' < '9' wins before the rest is even read.
  • Comparing dates as strings instead of converting to Date objects or timestamps first.

07 Interview Questions

Q: Why is '10' < '9' true?

String comparison is lexicographic (character by character) — '1' comes before '9', so the comparison resolves before the rest of the string is even considered.

Key Takeaway

Comparison operators always return a boolean; numbers compare by value, strings compare lexicographically, and mixed-type comparisons trigger coercion worth double-checking.

Related Concepts