Type Coercion
Type coercion (forced or implicit type conversion) is the process by which JavaScript automatically converts values from one type to another so that an operation can be performed.
JS is a dynamically and weakly typed language. So it "guesses" on its own how to coerce types if you mix them.
Types of type conversion
Implicit
JS does this automatically, without your involvement.
'5' + 2 // "52" → the number is converted to a string
'5' - 2 // 3 → the string is converted to a number
true + 1 // 2 → true → 1
false + 10 // 10 → false → 0Explicit
You do this deliberately using constructor functions.
Number('5'); // 5
String(123); // "123"
Boolean(0); // falseRules of implicit conversion
1. Conversion to a string
Happens during concatenation (+) when one of the operands is a string:
'Hello' + 5 // "Hello5"
true + '!' // "true!"
null + 'test' // "nulltest"If at least one operand is
string, both are coerced to a string.
2. Conversion to a number
Happens during arithmetic operations (-, *, /, %, **) or comparison.
'5' - 1 // 4
'10' * 2 // 20
'4' / '2' // 2
'abc' - 2 // NaN
true + true // 2
false * 5 // 0
null + 1 // 1
undefined + 1 // NaNThe exception is the
+operator, which can trigger string concatenation.
3. Conversion to a boolean
Happens in logical contexts:
if (...), while (...), !, ||, &&, and so on.
falsy values:
false
0
-0
0n (BigInt 0)
''
null
undefined
NaNEverything else is truthy.
Boolean(0); // false
Boolean(''); // false
Boolean('hello'); // true
Boolean([]); // true
Boolean({}); // trueComparison features
== - performs type coercion
=== - does not
0 == false // true (0 → false)
'5' == 5 // true ('5' → 5)
'' == false // true ('' → 0 → false)
null == undefined // true (a special rule)
[] == false // true ([] → 0 → false)
[] == ![] // true (explained below)0 === false // false
'5' === 5 // falseAn example of JS "magic": [] == ![]
Step by step:
[] == ![]![]→false(an empty array is truthy → it gets inverted)[] == false[]→0when comparedfalse→0
Result: 0 == 0 → true
Examples of non-obvious conversions
| Expression | Result | Why |
|---|---|---|
'5' + 1 | '51' | string + number → string |
'5' - 1 | 4 | string → number |
true + false | 1 | 1 + 0 |
10 + null | 10 | null → 0 |
10 + undefined | NaN | undefined → NaN |
'2' * '3' | 6 | both strings → numbers |
'2' + '3' | '23' | concatenation |
[] + [] | "" | both arrays → "" |
[] + {} | "[object Object]" | array → "", object → "[object Object]" |
Summary
| Conversion type | What triggers it | Example | Result |
|---|---|---|---|
| To string | + (if a string) | '5' + 2 | '52' |
| To number | - * / % < > == | '5' - 2 | 3 |
| To boolean | logical contexts | !!'js' | true |
Tip
To avoid unexpected conversions:
- always use strict comparison (
===) - perform explicit type conversion (
Number(),String(),Boolean()) - don't rely on JS's "automatic magic"
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.