The add operator + adds two value together:
var result = 1 + 2;
If the two operands are numbers, they perform an arithmetic add and return the result according to the following rules:
|If either operand is NaN|| the result is NaN.|
|If Infinity is added to Infinity|| the result is Infinity.|
|If -Infinity is added to -Infinity|| the result is -Infinity.|
|If Infinity is added to -Infinity|| the result is NaN.|
|If +0 is added to +0|| the result is +0.|
|If -0 is added to +0|| the result is +0.|
|If -0 is added to -0|| the result is -0.|
|If both operands are strings|| the second string is concatenated to the first.|
|If only one operand is a string|| the other operand is converted to a string and the result is the concatenation of the two strings.|
|If either operand is an object, number, or Boolean|| its toString() method is called to get a string |
value and then the previous rules regarding strings are applied.
For undefined and null, the String() function is called to retrieve the values "undefined" and "null", respectively.
var result1 = 5 + 5; //two numbers console.log(result1); //10 var result2 = 5 + "5"; //a number and a string console.log(result2); //"55"
Pay more attention to the following code
var num1 = 5; var num2 = 10; var message = "The sum of 5 and 10 is " + num1 + num2; console.log(message); //"The sum of 5 and 10 is 510"
Because each addition is done separately. The first combines a string with a number (5), which results in a string.
The second takes that result string and adds a number (10), which also results in a string.
To perform the arithmetic calculation and then append that to the string, add some parentheses like this:
var num1 = 5; var num2 = 10; var message = "The sum of 5 and 10 is " + (num1 + num2); console.log(message); //"The sum of 5 and 10 is 15"