Type coercion means that when the operands of an operator are different types, one of them will be converted to an “equivalent” value of the other operand’s type. For instance, if you do:
boolean == integer
the boolean operand will be converted to an integer: false
becomes 0
, true
becomes 1. Then the two values are compared.
However, if you use the non-converting comparison operator ===
, no such conversion occurs. When the operands are of different types, this operator returns false
, and only compares the values when they’re of the same type.
Coercion isn’t only done by comparison operators, although they’re the only ones that have both “strict” and “loose” variants. Most arithmetic operators will automatically converse non-numeric arguments to numbers, e.g. "50" / 5
is treated as 50 / 5
. There are also many built-in functions and methods that require string arguments; if you give them something else, they’ll automatically coerce them to strings.
But be careful — +
is both the arithmetic addition operator and the string concatenation operator — if you do string + number
, it converts the number to a string and concatenates, rather than converting the string to a number and adding. This is the source of many errors made when performing arithmetic on user input, since input is a string unless you explicitly convert it.
You can find a good explanation of JavaScript’s coercion rules in You Don’t Know JS and more reference-oriented documentation in MDN.