How to use Add Operator in Javascript
Description
The add operator +
is used in the following example:
var result = 1 + 2;
The add operator behaves differently for special values, as follows:
- If the two operands are numbers, perform an add.
- If either operand is NaN, the result is NaN.
- For Infinity + Infinity, the result is Infinity.
- For -Infinity + -Infinity, the result is -Infinity.
- If Infinity + -Infinity, the result is NaN.
- If +0 adds +0, the result is +0.
- If -0 adds to +0, the result is +0.
- If -0 adds -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 then concatenate.
- If either operand is an object, number, or Boolean, its toString() method is called to get a string value and then concatenate two strings.
- For undefined and null, the String() function is called to retrieve the values "undefined" and "null", respectively.
Example
var result1 = 1 + 5;
console.log(result1); //from w w w . j a v a 2 s.c o m
var result2 = 1 + "5";
console.log(result2);
var num1 = 1;
var num2 = 2;
var message = "The sum is " + num1 + num2;
console.log(message);
var message = "The sum is " + (num1 + num2);
console.log(message);
The code above generates the following result.