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.
Relational operators compare two values and 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.
Comparisons always return a boolean. Store the result when you need it later:
const ok = score >= passing
console.log(ok) // true or false
When you compare a number to a string, JavaScript coerces the string to a number if it looks numeric. That is convenient for form fields and query parameters, and dangerous when the string is not what you think.
Always parse and validate user input before range checks. Number('') is 0, and Number('abc') is NaN. Both can slip through loose comparisons if you are not watching.
For dates, compare numeric timestamps or Date objects directly. Comparing date strings lexicographically only works when the format sorts the same way time flows (ISO 8601 strings do).
NaN >= 0 is false, and so is NaN <= 0. The only reliable NaN check is Number.isNaN(value).
Predict the result of '10' > 2, '20' < '3', and NaN >= 0 before you run them in the console. If any result surprises you, note which type coercion caused it.
Lesson completed