Explicit and implicit type conversion
Explicit conversion
This is when you yourself explicitly specify that a value's type needs to change. That is, you perform the conversion intentionally.
You give the interpreter a direct instruction: "Make this a string / number / boolean".
Implicit conversion
This is when JavaScript itself automatically changes a data type while evaluating an expression, so the operation works.
The interpreter does this "for you", often unexpectedly.
Type conversion examples
1. Explicit conversion
You control the process yourself:
javascript
String(123); // "123"
Number("42"); // 42
Boolean(0); // false
Boolean("hi"); // trueOr using shorthand tricks:
javascript
123 + ""; // "123" (explicit conversion to a string)
+"42"; // 42 (conversion to a number)
!!"text"; // true (conversion to a boolean)The main point is that you make the conversion deliberately.
2. Implicit conversion
JS decides on its own what type to coerce values to so the operation becomes possible:
javascript
"5" * 2; // 10 ("5" → number)
"5" + 2; // "52" (2 → string)
1 == "1"; // true ("1" → number)
"10" - "5"; // 5
null + 1; // 1
undefined + 1; // NaNSometimes this leads to strange results:
javascript[] + {} // "[object Object]" [] + [] // "" true + false // 1
Key difference
| Comparison | Explicit conversion | Implicit conversion |
|---|---|---|
| Who decides | The developer | The JS engine |
| When it happens | When you explicitly call String(), Number(), etc. | Automatically while evaluating an expression |
| Example | Number("42") → 42 | "42" - 2 → 40 |
| Control | Full | Minimal |
| Risk of errors | Low | High (especially with == and +) |
Tips
- Use explicit conversion if you want to write predictable code.
- Avoid loose comparison (
==), use strict comparison (===) instead. - Check which operations trigger automatic coercion:
+- tends to coerce to a string-,*,/- coerce to a numberif,||,&&- coerce to a boolean
Comparison example:
javascript
// Explicit
const a = Number("5"); // 5
const b = String(true); // "true"
// Implicit
const c = "5" * 2; // 10 ("5" → number)
const d = "5" + 2; // "52" (2 → string)Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.