Implicit type coercion
Learn how implicit type coercion works with +, == and in if conditions.
Implicit type coercion
Sometimes JavaScript changes a value's type on its own while performing an operation. This is called implicit type coercion.
Example: in "5" + 3 the number 3 is turned into a string and the result is "53". That is because the + operator concatenates when one side is a string. But in "5" - 3 both sides are turned into numbers and the result is the number 2.
Conversion by operator
Knowing how each operator behaves prevents confusion. The + operator concatenates when one side is a string: "a" + 1 → "a1".
The -, * and / operators always expect numbers; they convert strings to numbers: "10" - 2 → 8, "6" * "2" → 12. When a string cannot become a number the result is NaN: "abc" * 2 → NaN.
Exercise Three-operator demo
Define a function called showCoercion. It should take a and b parameters. In the body write three lines: console.log(a + b), console.log(a - b) and console.log(a * b).
Show example solution
function showCoercion(a, b) {
console.log(a + b);
console.log(a - b);
console.log(a * b);
}
Exercise Call showCoercion with two type orders
The showCoercion function below is defined. Now call it twice: showCoercion("5", 3) and showCoercion(5, "3"). Put each call on its own line.
Show example solution
function showCoercion(a, b) {
console.log(a + b);
console.log(a - b);
console.log(a * b);
}
showCoercion("5", 3);
showCoercion(5, "3");
Test yourself
-
What does the expression "5" + 3 return?
console.log("5" + 3);- 8 (number)
- 53 (number)
- "53" (string)
- NaN
Show answer
"53" (string) — Correct. The + operator turns the other side into a string and concatenates when one side is a string; the result is "53".
-
Complete the concatenation expression
let result = "5" + ____; console.log(result);Show answer
let result = "5" + 3; console.log(result); -
Match the expression to its result
- "5" + 3
- "53"
- "5" - 3
- 2
- "5" * 2
- 10
- "abc" * 2
- NaN