Javascript Arithmetic Operators








Add Operator

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.

var result1 = 1 + 5;     
console.log(result1);    // ww w . j av  a 2 s .c om
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.





Subtract Operator

The subtract operator (-) is uses as follows:

var result = 2 - 1;

The subtract operator has special rules as follows:

  • If the two operands are numbers, do the subtract.
  • If either operand is NaN, the result is NaN.
  • For Infinity - Infinity, the result is NaN.
  • For -Infinity - -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.
  • For +0 - +0, the result is +0.
  • If -0 is subtracted from +0, the result is -0.
  • For -0 - -0, the result is +0.
  • If either operand is a string, a Boolean, null, or undefined, it is converted to a number using Number().
  • If either operand is an object, its valueOf() method is called to retrieve a numeric value.
  • If the object doesn't have valueOf() defined, then toString() is called and the resulting string is converted into a number.

var result1 = 8 - true;    //true is converted to 1
console.log(result1);//  w w  w  . j a  v  a 2  s .c om
var result2 = NaN - 1;     //NaN
console.log(result2);
var result3 = 8 - 3;       
console.log(result3);
var result4 = 8 - "";      //"" is converted to 0
console.log(result4);
var result5 = 8 - "2";     //"2" is converted to 2
console.log(result5);
var result6 = 8 - null;    //null is converted to 0
console.log(result6);

The code above generates the following result.





Multiply Operator

The multiply operator is represented by an asterisk *.

var result = 3 * 5;
console.log(result);

If either of the operands isn't a number, it is converted to a number behind the scenes using the Number() casting function. This means that an empty string is treated as 0, and the Boolean value of true is treated as 1.

The multiply operator has the following unique behaviors when dealing with special values:

  • If the operands are numbers, regular arithmetic multiplication is performed.
  • If the result is out of range, either Infinity or -Infinity is returned.
  • If either operand is NaN, the result is NaN.
  • For Infinity * 0, the result is NaN.
  • For Infinity * (any finite number other than 0), the result is either Infinity or -Infinity, depending on the sign of the second operand.
  • For Infinity * Infinity, the result is Infinity.
  • If either operand isn't a number, it is converted to a number using Number().

Divide Operator

The divide operator is represented by a slash /.

var result = 6 / 2;
console.log(result);

If either of the operands isn't a number, it is converted to a number behind the scenes using the Number() casting function. This means that an empty string is treated as 0, and the Boolean value of true is treated as 1.

The divide operator has special behaviors for special values.

  • If the operands are numbers, regular arithmetic division is performed.
  • If the result is out of range, it returns either Infinity or -Infinity.
  • If either operand is NaN, the result is NaN.
  • If Infinity is divided by Infinity, the result is NaN.
  • If zero is divided by zero, the result is NaN.
  • If a nonzero finite number is divided by zero, the result is either Infinity or -Infinity, depending on the sign of the first operand.
  • If Infinity is divided by any number, the result is either Infinity or -Infinity, depending on the sign of the second operand.
  • If either operand isn't a number, it is converted to a number using Number().

var result = 6 / 2;
console.log(result);

The code above generates the following result.

Unary Plus

The unary plus is represented by a single plus sign (+) placed before a variable and does nothing to a numeric value.


var num = 25;
console.log(num);
num = +num;    //still 25
console.log(num);

The code above generates the following result.

Unary Plus Conversion

When the unary plus is applied to a nonnumeric value, it performs the same conversion as the Number() casting function:

ParameterNumber Function Returns
Boolean true1
Boolean false0
null0
undefinedNaN
Empty string("")0
String with only number, for example "123"123
String with only number and plus sign, for example "+123"123
String with only number and minus sign, for example "-123"-123
Leading zeros are ignored, for example "0123"123
Leading zeros are ignored, for example "+0123"123
Leading zeros are ignored, for example "-0123"-123
String with valid floating-point format, such as "1.1"1.1
String with valid floating-point format, such as "+1.1"1.1
String with valid floating-point format, such as "-1.1"-1.1
Leading zeros are ignored, such as "01.1"1.1
String with hexadecimal format, "0xf"15
String with hexadecimal format, "-0xf"-15
String with not a number value, for example "asdf"NaN
objectsthe valueOf() method is called and the returned value is converted

The following example demonstrates the behavior of the unary plus when acting on different data types:


var s1 = "02";
var s2 = "1.2";
var s3 = "b";
var b = false;
var f = 1.1;
var o = {
    valueOf: function() {//from   www .  j  a  v a2s  .co m
        return -1;
    }
};

s1 = +s1;  
console.log(s1);
s2 = +s2;  
console.log(s2);
s3 = +s3;  
console.log(s3);
b = +b;    
console.log(b);
f = +f;    
console.log(f);
o = +o;
console.log(o);    

The code above generates the following result.

Unary Minus

The unary minus is represented by a single minus sign (-) placed before a variable.

Its primary use is to negate a numeric value

Unary Minus Conversion

When used on a numeric value, the unary minus simply negates the value.

When used on nonnumeric values, unary minus applies all of the same rules as unary plus and then negates the result.

ParameterNumber Function Returns
Boolean true1
Boolean false0
null0
undefinedNaN
Empty string("")0
String with only number, for example "123"123
String with only number and plus sign, for example "+123"123
String with only number and minus sign, for example "-123"-123
Leading zeros are ignored, for example "0123"123
Leading zeros are ignored, for example "+0123"123
Leading zeros are ignored, for example "-0123"-123
String with valid floating-point format, such as "1.1"1.1
String with valid floating-point format, such as "+1.1"1.1
String with valid floating-point format, such as "-1.1"-1.1
Leading zeros are ignored, such as "01.1"1.1
String with hexadecimal format, "0xf"15
String with hexadecimal format, "-0xf"-15
String with not a number value, for example "asdf"NaN
objectsthe valueOf() method is called and the returned value is converted

var s1 = "02";
var s2 = "1.2";
var s3 = "b";
var b = false;
var f = 1.1;
var o = {
    valueOf: function() {//from w  ww .j av  a2 s . co  m
        return -1;
    }
};

s1 = -s1;  
console.log(s1);
s2 = -s2;  
console.log(s2);
s3 = -s3;  
console.log(s3);
b = -b;    
console.log(b);
f = -f;    
console.log(f);
o = -o;
console.log(o);    

The code above generates the following result.

Modulus Operator

The modulus (remainder) operator is represented by a percent sign %.

If either of the operands isn't a number, it is converted to a number behind the scenes using the Number() casting function. This means that an empty string is treated as 0, and the Boolean value of true is treated as 1.

The modulus operator behaves differently for special values, as follows:

  • If the operands are numbers, regular arithmetic division is performed.
  • If the dividend is an infinite number and the divisor is a finite number, the result is NaN.
  • If the dividend is a finite number and the divisor is 0, the result is NaN.
  • If Infinity is divided by Infinity, the result is NaN.
  • If the dividend is a finite number and the divisor is an infinite number, then the result is the dividend.
  • If the dividend is zero and the divisor is nonzero, the result is zero.
  • If either operand isn't a number, it is converted to a number behind the scenes using Number().

var result = 26 % 5;    //equal to 1
console.log(result);

The code above generates the following result.

Increment Decrement

The increment and decrement operators is represented by ++ and -- respectively.

The increment and decrement operators have two versions: prefix and postfix.

The prefix versions of the operators are placed before the variable, while the postfix ones are placed after the variable.

To use a prefix increment, which adds 1 to a numeric value, you place two plus signs (++) in front of a variable like this:

var age = 29;
console.log(age);
++age;
console.log(age);

The code above is effectively equal to the following:

var age = 29;
console.log(age);
age = age + 1;
console.log(age);

The prefix decrement subtracts 1 from a numeric value. To use a prefix decrement, place two minus signs (--) before a variable, as shown here:

var age = 29;
console.log(age);
    --age;
console.log(age);

When using either a prefix increment or a prefix decrement, the variable's value is changed before the statement is evaluated.

var age = 29; 
var anotherAge = --age + 2; 
console.log(age);         //outputs 28
console.log(anotherAge);  //outputs 30

Postfix

The postfix versions of increment and decrement use the same syntax (++ and --, respectively) but are placed after the variable.

For postfix increment and decrement operators, the increment or decrement occur after the containing statement has been evaluated.

var num1 = 2;
console.log(num1);
var num2 = 20;
console.log(num2);
var num3 = num1-- + num2;    //equals 22
console.log(num3);
var num4 = num1 + num2;      //equals 21
console.log(num4);

The code above generates the following result.

All four of these operators work on any values including integers, strings, Booleans, floating-point values, and objects.

The increment and decrement operators follow these rules regarding values:

  • For a string with a valid number representation, convert to a number and apply the change.
  • For a string with not-valid-number representation, the variable's value is set to NaN.
  • For a false Boolean value, convert to 0 and apply the change.
  • For a true Boolean value, convert to 1 and apply the change.
  • For a floating-point value, apply the change by adding or subtracting 1.
  • For an object, call its valueOf() method to get a value. Apply the other rules. If the result is NaN, then call toString() and apply the other rules again.

The following example demonstrates some of these rules:


var s1 = "3";
var s2 = "z";
var b = false;
var f = 1.1;
var o = {
    valueOf: function() {/* www.ja v  a2 s . c om*/
        return -1;
    }
};

s1++;
console.log(s1);
s2++;
console.log(s2);
b++; 
console.log(b);
f--; 
console.log(f);
o--; 
console.log(o);

The code above generates the following result.

Assignment Operators

Simple assignment is = as shown in the following example.

var num = 1;

Compound assignment operators are shorthand for the simple assignment.

var num = 1;
num = num + 1;
console.log(num);

The second line of code can be replaced with a compound assignment:

var num = 1;
num += 1;
console.log(num);

Compound-assignment operators in Javascript are as follows:

  • Multiply/assign (*=)
  • Divide/assign (/=)
  • Modulus/assign (%=)
  • Add/assign (+=)
  • Subtract/assign (-=)
  • Left shift/assign (<<=)
  • Signed right shift/assign (>>=)
  • Unsigned right shift/assign (>>>=)