JavaScript
/Intermediate
Implicit vs Explicit Type Conversion
Definition
Explicit conversion (Type Casting) is when a developer manually converts one data type to another using functions like `Number()`. Implicit conversion (Type Coercion) is when JavaScript automatically converts types behind the scenes.
Explain Like I'm New
Explicit is you translating English to Spanish with a dictionary. Implicit is JavaScript trying to guess the translation on the fly, sometimes ending up saying something completely embarrassing.
Real World Example
Explicit: Reading an `<input value="10" />` and explicitly calling `parseInt(value, 10)` before doing math. Implicit: Just doing `value * 5`, letting JS guess that you wanted a number.
Common Use Cases
- •Parsing user input
- •Avoiding NaN errors
Terminal Output
bash / terminal
// EXPLICIT (Clear and safe)
const num = Number("42");
// IMPLICIT (Magic and dangerous)
const implicitNum = "42" * 1;
console.log(1 + "2" + "2"); // "122"
console.log(1 + +"2" + "2"); // "32" (The unary plus coercies "2" to 2 first)
Interview Questions
basic
- What is type coercion?
intermediate
- What happens when you add an array to an object: `[] + {}`?
advanced
- How does the `valueOf()` and `toString()` mechanism work during coercion?