Addition is about adding numbers.
Concatenation is about adding strings.
In JavaScript both operations use the same +
operator.
Because of this, adding a number as a number will produce a different result from adding a number as a string:
var x = 10 + 5; // the result in x is 15
var x = 10 + "5"; // the result in x is "105"
var x = 10 + "5"; // the result in x is "105"
When adding two variables, it can be difficult to anticipate the result:
var x = 10;
var y = 5;
var z = x + y; // the result in z is 15
var x = 10;
var y = "5";
var z = x + y; // the result in z is "105"
var y = 5;
var z = x + y; // the result in z is 15
var x = 10;
var y = "5";
var z = x + y; // the result in z is "105"
Practice Excercise Practice now