Type Coercion — *The Traps of ==*
Type Coercion — *The Traps of ==*
🎯 By the End of This Lesson
After finishing this lesson, you'll be able to confidently handle the following three things.
- ▸✅ How implicit conversion works with
==/+/- - ▸✅ The 6 falsy values (0 · '' · null · undefined · NaN · false)
- ▸✅ The exact behavior of
Object.is/Number.isNaN
Keep the learning objectives as a checklist — close the lesson only once you can answer all of them.
== vs === — *Always Use ===*
The Core Rule in One Line
JavaScript's == coerces types before comparing. Unexpected results are par for the course. Always use ===.
The Shocking Behavior of ==
Look at that last line. An array equals its own negation. The insane result of JS implicit conversion.
=== — Safe Comparison
=== is true only when both value and type match. Predictable.
Why ESLint Enforces This
Most lint configurations enable the eqeqeq rule by default. New code should always use ===. Once you get used to it, seeing == starts to feel uncomfortable.
> Exception: when you want to catch both null and undefined:
Only this one pattern is permitted in some code styles. Otherwise, always use ===.
Truthy / Falsy
Use if (value) as a quick check for whether a value exists. But be aware of pitfalls like empty arrays and "0".
The Most Common Pitfalls
1. Comparing input values:
2. Numbers from JSON:
JSON preserves types, so it's generally safe. However, large integers need to be converted to bigint.
Summary
- ▸Always use
===.==produces unexpected results - ▸Remember that empty arrays and
"0"are also truthy - ▸Explicitly convert input values before comparing
⚡ Try It Yourself — == vs ===
🤖 Try Prompting AI Like This
Once you understand the concepts in this lesson, you can give AI specific instructions — not vague requests like "fix this," but vocabulary-driven prompts. That's where token savings start.
- ▸"Add appropriate TypeScript type annotations to this variable"
- ▸"Unify the mixed use of === and == to === and make the intent clear"
- ▸"Add an unknown type + type guard to the JSON.parse result in this code"
Why This Saves Tokens
Without knowing the concepts, you'd receive an AI response and still need to ask "What does that mean?" again. That follow-up question burns tokens. Learn the concept once and the conversation ends in one round.