iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

JS Comparisons

JavaScript has two equality operators: strict (===) and loose (==). Strict is almost always what you want.

=== vs ==

Expression=====
5 === "5"falsetrue (coerces string to number)
0 === falsefalsetrue
null === undefinedfalsetrue
NaN === NaNfalsefalse (NaN is never equal to anything, including itself)
[] === []falsefalse (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)) { /* … */ }

Test yourself

Q1. Recommended equality operator is…
Q2. `NaN === NaN` is…
Q3. Best test for NaN is…

Discussion

Loading…