Skip to content

Type Coercion

Medium — good to knowFrontend

ELI5 — The Vibe Check

Type coercion is JavaScript's 'helpful' habit of automatically converting types when you didn't ask it to. '5' + 3 equals '53' (string). '5' - 3 equals 2 (number). + {} equals 'object Object' (what?). It's the source of every JavaScript meme and the reason TypeScript exists. The loose equality operator (==) is coercion's best friend and your worst enemy.

Real Talk

Type coercion is the automatic or implicit conversion of values from one type to another. JavaScript is particularly aggressive with coercion, applying the Abstract Equality Comparison Algorithm for == and various ToString/ToNumber/ToBoolean conversions. TypeScript, strict equality (===), and explicit conversion functions help avoid coercion bugs.

Show Me The Code

// JavaScript coercion madness
'5' + 3      // '53' (string concatenation)
'5' - 3      // 2 (numeric subtraction)
true + true  // 2
[] + []      // '' (empty string)
[] + {}      // '[object Object]'
{} + []      // 0

// The fix: strict equality
0 == ''      // true (coercion!)
0 === ''     // false (no coercion)

When You'll Hear This

"Type coercion is why '1' + 1 equals '11' in JavaScript." / "Use === always — type coercion is a footgun."

Made with passive-aggressive love by manoga.digital. Powered by Claude.