Lesson 45 of 296
Type coercion
What you will learn
- What type coercion is
- Explicit and implicit conversion
- The three conversions: to string, to number, to boolean
- How
+,-,==and comparisons convert values - How objects and arrays convert
- How to answer "predict the output" questions
On this page
- What is type coercion?
- Converting to string
- Converting to number
- Converting to boolean
- How objects convert
- The + operator
- The other maths operators
- Loose equality ==
- Relational comparison < > <= >=
- How to solve "predict the output" questions
- The professional rule
- Common mistakes
- How to say it in an interview
- Key words
What is type coercion?
Type coercion means converting a value from one type to another. There are two kinds:
- Explicit (you ask for it):
Number("5"),String(5),Boolean(0). - Implicit (JavaScript does it by itself):
"5" * 2gives10.
JavaScript only ever converts to three types: string, number or boolean. If you know the rules for these three, you can predict almost every result.
Converting to string
| Value | String(value) |
|---|---|
42 | "42" |
true | "true" |
null | "null" |
undefined | "undefined" |
[1, 2, 3] | "1,2,3" |
[] | "" |
{} | "[object Object]" |
Converting to number
| Value | Number(value) |
|---|---|
"42" | 42 |
" 42 " | 42 (spaces at the ends are ignored) |
"42px" | NaN |
"" | 0 |
true / false | 1 / 0 |
null | 0 |
undefined | NaN |
[] | 0 (becomes "", then 0) |
[5] | 5 (becomes "5", then 5) |
[1, 2] | NaN (becomes "1,2") |
{} | NaN |
Converting to boolean
Only 8 values become false (Lesson 46). Everything else becomes true.
How objects convert
When an object or array must become a primitive, JavaScript calls its valueOf() method, and if that does not give a primitive, its toString() method. For arrays, toString() joins the items with commas. For plain objects it gives "[object Object]". This is why [] becomes "" and {} becomes "[object Object]".
The + operator
+ does two jobs: adding and joining.
- Convert both sides to primitives.
- If either side is a string, convert both to strings and join.
- Otherwise convert both to numbers and add.
1 + 2 3
"1" + 2 "12"
1 + "2" "12"
1 + 2 + "3" "33" (left to right: 1 + 2 = 3, then 3 + "3")
"1" + 2 + 3 "123" ("1" + 2 = "12", then "12" + 3)
true + 1 2 (true becomes 1)
null + 1 1 (null becomes 0)
undefined + 1 NaN
[] + [] "" (both become "")
[] + {} "[object Object]"
[1] + [2] "12"The other maths operators
-, *, /, % and ** always convert to numbers:
"6" - 2 4
"6" * "2" 12
"abc" - 1 NaN
[] - 1 -1
true * 3 3Unary plus converts to a number:
+"42" 42
+"" 0
+true 1Loose equality ==
The main rules of ==:
- Same type: compare like
===. null == undefinedistrue. Neither is loosely equal to anything else.- Number and string: convert the string to a number.
- Boolean and anything: convert the boolean to a number first.
- Object and primitive: convert the object to a primitive first.
"1" == 1 true (rule 3)
true == 1 true (rule 4)
true == "1" true (true becomes 1, then "1" becomes 1)
true == "true" false (true becomes 1, "true" becomes NaN)
null == 0 false (rule 2)
[] == false true (false becomes 0, [] becomes "" then 0)
[] == ![] true (![] is false, then as above)[] == ![] is a famous trick question. Walk through it slowly: ![] is false because [] is truthy. Then [] == false, which is 0 == 0, which is true.
Relational comparison < > <= >=
- Two strings: compared character by character (Lesson 33).
- Otherwise: both converted to numbers.
"10" < "9" true (text comparison)
"10" < 9 false (number comparison)
null >= 0 true (null becomes 0)
undefined >= 0 false (undefined becomes NaN, and NaN comparisons are always false)How to solve "predict the output" questions
- Find the operator.
- Check its rule:
+(string wins), other maths (numbers),==(the steps above). - Convert one step at a time and write each step down.
- Work left to right for chains like
1 + 2 + "3".
The professional rule
Interviewers ask about coercion to test your understanding, not because good code depends on it. In real code:
- Always use
===. - Convert explicitly:
Number(input),String(id). - Use TypeScript to catch mixed types early.
Common mistakes
- Forgetting that
+joins if either side is a string. - Forgetting the left-to-right order in
1 + 2 + "3". - Assuming
Number("")isNaN(it is0). - Assuming
[]is falsy (it is truthy, but[] == falseis true because of conversion).
How to say it in an interview
"Type coercion is JavaScript converting values between types. Values are only ever converted to string, number or boolean. The plus operator concatenates if either operand is a string, otherwise it adds numbers; the other arithmetic operators always convert to numbers. Loose equality converts booleans to numbers and objects to primitives, and treats null and undefined as equal only to each other. Objects convert through valueOf and toString, which is why an empty array becomes an empty string. In real code I avoid implicit coercion by using strict equality and explicit conversions."
Key words
| Word | Meaning |
|---|---|
| Type coercion | Converting a value to another type |
| Explicit conversion | Conversion you write yourself, like Number(x) |
| Implicit conversion | Conversion JavaScript does automatically |
| Primitive conversion | Turning an object into a primitive via valueOf or toString |
| Unary plus | +x, a short way to convert to a number |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.