Skip to the content

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?

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" * 2 gives 10.

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

ValueString(value)
42"42"
true"true"
null"null"
undefined"undefined"
[1, 2, 3]"1,2,3"
[]""
{}"[object Object]"

Converting to number

ValueNumber(value)
"42"42
" 42 "42 (spaces at the ends are ignored)
"42px"NaN
""0
true / false1 / 0
null0
undefinedNaN
[]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.

  1. Convert both sides to primitives.
  2. If either side is a string, convert both to strings and join.
  3. 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         3

Unary plus converts to a number:

+"42"            42
+""              0
+true            1

Loose equality ==

The main rules of ==:

  1. Same type: compare like ===.
  2. null == undefined is true. Neither is loosely equal to anything else.
  3. Number and string: convert the string to a number.
  4. Boolean and anything: convert the boolean to a number first.
  5. 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

  1. Find the operator.
  2. Check its rule: + (string wins), other maths (numbers), == (the steps above).
  3. Convert one step at a time and write each step down.
  4. 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("") is NaN (it is 0).
  • Assuming [] is falsy (it is truthy, but [] == false is 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

WordMeaning
Type coercionConverting a value to another type
Explicit conversionConversion you write yourself, like Number(x)
Implicit conversionConversion JavaScript does automatically
Primitive conversionTurning 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.