Chapters

FundamentalsChapter 14 of 21

Comparison

Testing values against each other, and the traps in ordering them.

The operators

Comparison produces a boolean. Six of them matter, and this tutorial uses === and !== throughout for reasons the equality chapter covers.

JavaScript

JavaScript

console.log(5 === 5);
console.log(5 !== 3);
console.log(5 > 3);
console.log(5 < 3);
console.log(5 >= 5);
console.log(5 <= 4);

Output

true
true
true
false
true
false

Comparing strings

The ordering operators work on strings too, comparing character by character using their code point. That is not alphabetical order.

JavaScript

JavaScript

console.log('apple' < 'banana');
console.log('Zebra' < 'apple');
console.log('10' < '9');

Output

true
true
true

Capitals sort before lowercase, and digits compare as text, so the string "10" really is less than "9". For anything a person will read, use localeCompare:

JavaScript

JavaScript

const names = ['Zebra', 'apple', 'Banana'];

console.log(names.slice().sort());
console.log(names.slice().sort((a, b) => a.localeCompare(b)));

Output

["Banana", "Zebra", "apple"]
["apple", "Banana", "Zebra"]

Mixed types

The ordering operators convert their operands to numbers first, which produces some odd but explainable results.

JavaScript

JavaScript

console.log('10' > 9);
console.log(true > 0);
console.log(null >= 0);
console.log(null > 0);

Output

true
true
true
false

Gotcha

null >= 0 is true while null > 0 is false, because the two use different rules. Comparing values of different types is where JavaScript is at its least intuitive, so convert deliberately first.

Comparing objects

Objects and arrays compare by identity, not contents. Two separately built objects are never equal, however alike they look.

JavaScript

JavaScript

const a = { id: 1 };
const b = { id: 1 };
const c = a;

console.log(a === b);
console.log(a === c);
console.log(JSON.stringify(a) === JSON.stringify(b));

Output

false
true
true

The last line is a rough way to compare contents. It is fine for simple data and wrong for anything with functions, dates or a different key order.

Test yourself

2 questions

Why is the string "10" less than the string "9"?

Show the answer

Strings compare character by character, and "1" comes before "9" The comparison never gets past the first character.

When are two objects ===

Show the answer

Only when they are the same object Identity, not contents, which is why two identical-looking literals are never equal.

Next chapter

Logical

Combining conditions, and using and, or and nullish for defaults.