- To see whether a string is greater than another, JavaScript uses the so-called “dictionary” or “lexicographical” order.
- In other words, strings are compared letter-by-letter.
- The algorithm to compare two strings is simple:
- Compare the first character of both strings.
- If the first character from the first string is greater (or less) than the other string’s, then the first string is greater (or less) than the second.
- Otherwise, if both strings’ first characters are the same, compare the second characters the same way.
- If both strings end at the same length, then they are equal.
- Otherwise, the longer string is greater.
- When comparing values of different types, JavaScript converts the values to numbers.
console.log('2' > 1); // true, string '2' becomes a number 2
console.log('01' == 1); // true, string '01' becomes a number 1
let a = 0;
console.log(Boolean(a)); // false
let b = "0";
console.log(Boolean(b)); // true
console.log(a == b); // true
Strict Equality
- A regular equality check
==
cannot differentiate 0 from false.
- The same thing happens with an empty string.
- This happens because operands of different types are converted to numbers by the equality operator.
console.log(0 == false); // true
console.log('' == false); // true
- A strict equality operator
===
checks the equality without type conversion.
console.log( 0 === false ); // false, because the types are different
Comparison with null
and undefined
- There’s a non-intuitive behavior when
null
or undefined
are compared to other values.
null
and undefined
are equal to each other (in the sense of ==), but not any other value.
console.log(null == undefined); // true
- An equality check
==
and comparisons > < >= <=
work differently.
- When it comes to math comparisons,
null
/undefined
are converted to numbers.
null
becomes 0, while undefined
becomes NaN
.
- That’s why
null >= 0
is true and null > 0
is false.
- On the other hand, the equality check
==
for undefined
and null
is predefined to be equal to each other and don’t equal anything else.
- That’s why
null == 0
is false.
- In general, the value
undefined
shouldn’t be compared to other values.
undefined
gets converted to NaN
and NaN
returns false
for all comparisons.
- The equality check of
undefined
only equals to null
and no other value.
- Generally, treat any comparison with
undefined
/null
except the strict equality ===
with extra care.
- Don’t use comparisons >= > < <= with a variable which may be
null
/undefined
, unless you’re really sure of what you’re doing.
- If a variable can have these values, check for them separately.
console.log(NaN == NaN); // false
console.log(undefined == undefined); // true
console.log(null == null); // true
console.log(undefined == null); // true