JavaScript Course
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?

Flash Cards

Question

What happens in `[] + {}`?

Click to reveal answer
Answer

JavaScript converts both to strings to concatenate them. `[]` becomes `""` (empty string). `{}` becomes `"[object Object]"`. The result is `"[object Object]"`.

Question

How do valueOf and toString work?

Click to reveal answer
Answer

When JS tries to coerce an object to a primitive, it first calls `valueOf()`. If that doesn't return a primitive, it falls back to calling `toString()`. You can override these methods to change an object's math behavior.