The additive operators are part of the arithmetic operators.

There are two additive operators; these are add ("+") and subtract ("-"). These operators work with two values that don't necessarily have to be numbers, in which case they are converted to numbers behind the scene.

Add

The add operator is represented by an add symbol ("+") and it is used to add two values together, as shown in the example:

var add = 700 + 4;

When the two operands are made of special characters, these rules apply:

  • If either number 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

When one of the operands is a string, these rule apply:

  • If both operands are strings, the 2nd string is concatenated to the first (added literally);
  • If only one is a string, the other is converted into a string and the result is concatenation of two strings.

Any other data types, i.e. object, null, undefined, will first be converted to their string values and then the rules from above will apply.

Due to these rules it is always import to keep in mind the data types. The following example illustrates that better:

var num1 = 10;

var num2 = 12;

var text1 = "The sum of 10 and 12 is: " + num1 + num2; //result = 1012

var text2 = "The sum of 10 and 12 is: " + (num1 + num2); //result = 22

In the example the correct calculation is with the variable "text2" because the numbers are added under the parenthesis, thus being calculated the first. The variable "text1" has no parenthesis so the numbers are converted into strings first and just added together. The rules above explain why that happens.

Subtract

The subtract operator is represented by a subtract symbol ("-") and it is used to subtract two values together, as shown in the example:

var add = 700 - 4;

When the two operands are made of special characters, these rules apply:

  • If either number is NaN, the result is NaN;
  • If Infinity is subtracted from Infinity, the result is NaN;
  • If -Infinity is subtracted from -Infinity, the result is NaN;
  • If -Infinity is subtracted from Infinity, the result is Infinity;
  • If Infinity is subtracted from -Infinity, the result is -Infinity;
  • If any of the operands is an object, a string, a Boolean, null, or undefined it is converted to a number and the regular operation is performed.

Example

The example with additive (arithmetic) operators in JavaScript:

 

›› go to examples ››