JavaScript Tutorial
JavaScript Comparisons
=== checks value and type. == coerces. Prefer === so "5" and 5 stay different.
Equal in two different ways
=== is strict equality: same value and same type. == is loose equality: JavaScript converts one side, then compares. That conversion is called coercion, and it is how"5" == 5 becomes true.
Prefer === in this tutorial and in your own scripts. When a string and a number should stay different, strict equality is the tool that keeps them different.
Log both operators in /javascript/try. The two results for"5" and 5 are the whole lesson.
=== checks value and type
Numbers compare as numbers. Strings compare as strings. A number is never strictly equal to a string of digits. true is not 1 under ===.
Example
console.log(5 === 5);
console.log("5" === "5");
console.log("5" === 5);
console.log(true === 1);
console.log(null === undefined);
document.body.textContent =
String("5" === 5) + " strict / " + String(5 === 5) + " number";
== coerces
Loose equality converts before it compares. "5" == 5 is true because the string becomes the number 5. true == 1 is true. null == undefined istrue, which is a special case in the spec.
Example
console.log("5" == 5);
console.log(true == 1);
console.log(false == 0);
console.log("" == 0);
console.log(null == undefined);
console.log(null == 0);
document.body.textContent =
String("5" == 5) + " loose / " + String("" == 0);
"" == 0 is true. An empty input from a form is not the number zero, but== will treat it that way. That is a real bug in score and quantity code.
Not equal
!== is the strict opposite of ===. != is the loose opposite of==. Use !== with the same discipline you use for ===.
| Operator | True when |
|---|---|
=== | Same value and same type |
!== | Different value or different type |
== | Equal after coercion |
!= | Not equal after coercion |
Ordering
<, <=, >, and >= compare numbers in the obvious way. They also coerce: "10" > 2 is true because the string becomes a number. If both sides are strings, they compare alphabetically: "10" > "2" isfalse because "1" comes before "2".
Example
console.log(10 > 2);
console.log("10" > 2);
console.log("10" > "2");
console.log(7 <= 7);
console.log("apple" < "banana");
document.body.textContent =
String("10" > 2) + " coerced / " + String("10" > "2") + " text";
NaN is never equal
NaN === NaN is false. NaN == NaN is also false. After a failed Number(...) conversion, use Number.isNaN(value), not an equality check.
Example
const n = Number("wait");
console.log(n === n);
console.log(n == n);
console.log(Number.isNaN(n));
document.body.textContent = "isNaN " + String(Number.isNaN(n));
What to remember
- Default to
===and!==. "5"and5are different under strict equality.- Ordering coerces too. Convert on purpose, then compare numbers to numbers.
- Never test
NaNwith===.
Next: if, else if, and else — run a block when a test is true.