What is type coercion in JavaScript?
Answer
Type coercion is the automatic or explicit conversion of values from one type to another. Implicit coercion happens automatically: "5" + 3 → "53" (string concatenation takes priority), "5" - 3 → 2 (subtraction forces numeric). if ("hello") → truthy coercion. !!"hello" → true. Coercion rules: + with a string → string; arithmetic operators (-, *, /) → numbers; comparison <, > between strings → lexicographic; between mixed → numeric. Explicit coercion: Number("42"), String(42), Boolean(0), parseInt("42px"). Famous coercion oddities: [] + [] → "", [] + {} → "[object Object]", {} + [] → 0 (if {} is a block). This is why === is preferred — it skips coercion. Understanding coercion is important for reading legacy code and debugging unexpected values. The abstract equality algorithm (==) defines coercion rules in detail.
Previous
What is the difference between for...in and Object.keys()?
Next
What is the difference between Array.find() and Array.filter()?