Values and variables

JavaScript Comparison Operators

Learn how the JavaScript comparison operators less than, greater than and their or-equal variants compare numbers, and how they order strings by Unicode value.

8 minute lesson

~~~

Relational comparison operators return a boolean:

  • < less than
  • <= less than or equal to
  • > greater than
  • >= greater than, or equal to
const a = 2
a >= 1 //true

With two numbers, the meaning is direct. With two strings, JavaScript compares UTF-16 code units lexicographically, not human dictionary order:

'20' < '3'       // true: '2' comes before '3'
'Zebra' < 'apple' // true: uppercase Z has a lower code unit

Convert numeric input before comparing it:

const quantity = Number(input.value)

if (Number.isFinite(quantity) && quantity >= 1) {
  addItems(quantity)
}

Mixed-type comparisons perform coercion and can hide mistakes:

'10' > 2 // true, because '10' becomes 10

Prefer comparing values of the same expected type. For user-facing string sorting, use Intl.Collator or localeCompare() because language rules, accents, and case are more complex than code-unit order:

const names = ['Åsa', 'Ana', 'zoe']
names.sort(new Intl.Collator('en', { sensitivity: 'base' }).compare)

NaN is neither less than, greater than, nor equal to another number. Validate parsed values before using a comparison as a range check.

Try it: predict the result of five comparisons involving numbers, numeric strings, case differences, and NaN, then run them and explain every coercion.

Lesson completed