Type Coercion
Type Coercion
Section titled “Type Coercion”Introduction
Section titled “Introduction”Type coercion is JavaScript’s implicit type conversion — when JavaScript automatically converts a value to another type during operations.
Why Do We Need This?
Section titled “Why Do We Need This?”Coercion happens everywhere in JavaScript. Understanding it is essential to avoid bugs that seem like magic.
Real World Story
Section titled “Real World Story”Coercion is like a restaurant that adapts your order. You ask for “2” beers (string), and the waiter brings 2 beers (number). It’s convenient, but sometimes you get something unexpected.
Visual Explanation
Section titled “Visual Explanation”flowchart TD A["'5' - 3"] --> B["2 (number)"] C["'5' + 3"] --> D["'53' (string)"] E["'5' * '2'"] --> F["10 (number)"] G["!'hello'"] --> H["false (boolean)"]Common Coercion Patterns
Section titled “Common Coercion Patterns”// String coercion with +'5' + 3; // '53''5' + true; // '5true''5' + null; // '5null'
// Number coercion with -, *, /'5' - 3; // 2'10' * '2'; // 20'10' / '2'; // 5
// Boolean coercionif ('hello') {} // truthyif (0) {} // falsy!'hello'; // false!!'hello'; // trueLoose Equality (==)
Section titled “Loose Equality (==)”5 == '5'; // true0 == false; // true'' == false; // truenull == undefined; // trueBest Practices
Section titled “Best Practices”- Use
===and!==instead of==and!= - Be explicit with conversions — don’t rely on coercion
- Use
Number.isNaN()instead of globalisNaN()
Common Mistakes
Section titled “Common Mistakes”[] == false; // true — surprising![] == ![]; // true — the famous JavaScript wtfSummary
Section titled “Summary”- Coercion is implicit type conversion
+prefers string concatenation-,*,/prefer numeric conversion- Always use
===to avoid coercion surprises