What is the difference between implicit and explicit type coercion?
Explicit coercion is when you convert on purpose, like Number("5") or String(5). Implicit coercion is when JavaScript converts for you during an operation, like "5" * 2 or if (value).
Explain it simply
Explicit coercion is you handing over the right currency yourself: you write Number(input) and the intent is obvious. Implicit coercion is the shopkeeper converting for you without asking: "5" * 2 quietly turns the string into a number.
Implicit coercion happens with arithmetic (-, *, /), loose equality (==), conditions (if, &&, ||, !) and the + operator when one side is a string.
Implicit is not always bad: if (name) is idiomatic. The risk is in mixed types, such as "5" + 2, where the result depends on rules most readers do not remember.
Example
// explicit
console.log(Number("7") + 1); // Output: 8
console.log(String(7) + 1); // Output: 71
console.log(Boolean("hi")); // Output: true
// implicit
console.log("7" * 2); // Output: 14
console.log("7" + 2); // Output: 72
console.log(true + 1); // Output: 2
console.log(null + 1); // Output: 1
console.log(String(undefined + 1)); // Output: NaNWhat to say in the interview
"Explicit coercion uses Number(), String() or Boolean() and states the intent. Implicit coercion is done by the engine inside operators. I rely on implicit conversion only in simple truthiness checks, and convert explicitly whenever types are mixed."
Common mistakes
- Assuming + behaves like - . Plus prefers strings; minus always makes numbers.
- Thinking null and undefined both become 0. Only null does; undefined becomes NaN.