How to use Subtract Operator in Javascript
Description
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.
Example
var result1 = 8 - true; //true is converted to 1
console.log(result1);//from w w w. ja v a 2 s .c o m
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.