Course outline · 0% complete

0/27 lessons0%

Course overview →

Equality and coercion

lesson 10-2 · ~12 min · 26/27

Two equality operators

  • === (strict): equal only if the type and value both match. No conversions, no surprises.
  • == (loose): if the types differ, JavaScript coerces the operands (usually toward numbers) before comparing. That is where the party tricks come from: 1 == "1", [] == false, null == undefined are all true.

And one special number: NaN ("not a number", the result of failed math like Number("abc")) is the only value not equal to itself. Check for it with Number.isNaN(x), never with === NaN.

Coercion questions are interview standards, but the production reason to care is sharper: == bugs pass code review silently and surface later as corrupted data or impossible states. Knowing the actual rules is what lets you write === with confidence instead of superstition.

Code exercise · javascript

Run it and read each line against the rules above. The last pair is the NaN self-inequality every interviewer eventually asks about.

Quiz

What does `[] == false` evaluate to, and why?

The rule to say out loud

Use === always. The one accepted exception: x == null is a deliberate idiom that is true exactly when x is null or undefined, a compact version of the ?? reasoning from lesson 8-2.

Bonus float gotcha (not coercion, but asked in the same breath): binary floating point cannot represent 0.1 or 0.2 exactly, so their sum is 0.30000000000000004. Compare floats with a tolerance, not equality. Try that one below.

Problem

One word, true or false: what does `0.1 + 0.2 === 0.3` evaluate to in JavaScript?

Code exercise · javascript

Your turn, the fix for what you just predicted. Implement `approxEqual(a, b)`: true when a and b differ by less than 1e-9. This tolerance check is the standard way to compare float results.