JS Comparisons
JavaScript has two equality operators: strict (===) and loose (==). Strict is almost always what you want.
=== vs ==
| Expression | === | == |
|---|---|---|
5 === "5" | false | true (coerces string to number) |
0 === false | false | true |
null === undefined | false | true |
NaN === NaN | false | false (NaN is never equal to anything, including itself) |
[] === [] | false | false (different objects) |
Comparing objects
JS
// Reference comparison — two literals are different objects
{} === {} // false
[1] === [1] // false
const a = { x: 1 };
const b = a;
a === b // true — same reference
// Value comparison needs a helper
JSON.stringify(a) === JSON.stringify(b) // shallow shortcut, fragile
// or use lodash _.isEqual / your own deepEqual
Ordering: < > <= >=
JS
"apple" < "banana" // true — lexicographic "10" < "9" // true! string comparison 10 < "9" // false — coerced to numbers "a" < 1 // false — NaN comparisons return false
Special case:
null == undefined is true, but null === undefined is false. The ?? operator treats both as "missing" — useful when you want either to trigger a fallback.Tip: Use
Number.isNaN(x) to test for NaN — the global isNaN coerces its argument and gives wrong answers for non-numeric strings.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS Comparisons!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Safely test for NaN.
if (
.isNaN(x)) { /* … */ }
The modern, type-checking variant.
Discussion
Loading…