- Home
- /
- Tutorials
- /
- JavaScript Tutorial
- /
- JavaScript Type Coercion
JavaScript Type System
JavaScript Type Coercion
Type coercion is JavaScript converting types automatically, whether you wanted it or not.
It is the reason "5" + 3 and "5" - 3 give completely different answers.
Understanding it removes most of JavaScript's reputation for strangeness.
Example
Example
javascript
console.log("5" + 3);
console.log("5" - 3);The output is 53 then 2.
Plus joined them; minus converted them.
Why It Happens
Most operators expect numbers, so they convert what they are given.
+ is the exception: if either side is a string, it joins instead.
Comparisons with == also convert, which is the next lesson.
Syntax
Syntax
javascript
"5" + 3 // "53" — joined
"5" - 3 // 2 — convertedOnly + prefers joining.
The Plus Operator
If either side is a string, the whole thing becomes a string.
Example
Example
javascript
console.log(1 + 2 + "3");
console.log("1" + 2 + 3);The first adds 1 and 2 first, giving 33.
The second joins from the start, giving 123.
Every Other Operator Converts
Minus, multiply and divide always work with numbers.
Example
Example
javascript
console.log("10" - 5);
console.log("10" * 2);
console.log("10" / 2);The output is 5, 20, 5.
Booleans Become Numbers
true is 1 and false is 0 in arithmetic.
Example
Example
javascript
console.log(true + 1);
console.log(false + 1);
console.log(true + true);The output is 2, 1, 2.
The Famous Oddities
These come up in interviews constantly.
Each one follows the rules above, however strange it looks.
Example
Example
javascript
console.log([] + []);
console.log([] + {});
console.log(1 + "2" - 1);An empty array becomes an empty string, which explains the first two.
How to Avoid Surprises
Convert deliberately before doing arithmetic.
Then the operators never have to guess.
Example
Example
javascript
const entered = "10";
console.log(Number(entered) + 5);The output is 15, with no ambiguity.
Complete Example
Complete Example
html
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Type Coercion</title>
</head>
<body>
<h1>Type Coercion</h1>
<p id="out"></p>
<script>
const lines = [
'"5" + 3 = ' + ("5" + 3),
'"5" - 3 = ' + ("5" - 3),
'true + 1 = ' + (true + 1),
'1 + "2" = ' + (1 + "2"),
'Number("5") + 3 = ' + (Number("5") + 3)
];
document.getElementById("out").innerHTML = lines.join("<br>");
</script>
</body>
</html>Try It Yourself
Run the above example in the Try It Editor.
Try predicting first:
Cover the answers, guess each one, then check.
Important Points
- Coercion is automatic type conversion.
+joins when either side is a string.- Every other arithmetic operator converts to numbers.
trueis 1 andfalseis 0.- Convert deliberately and the surprises disappear.
Conclusion
Coercion is not random; it follows a small set of rules.
The + operator is the one exception worth memorising.
Explicit conversion is how you stay out of trouble.
