The subtract operator (-) is used as follows:
let result = 2 - 1;
The subtract operator has special rules to deal with the variety of type conversions present in Javascript.
They are as follows:
NaN
, the result is NaN
. NaN
. NaN
. Number()
and the arithmetic is calculated using the previous rules. If that conversion results in NaN, then the result of the subtraction is NaN. valueOf()
method is called to retrieve a numeric value to represent it. If that value is NaN, then the result of the subtraction is NaN. valueOf()
defined, then toString()
is called and the resulting string is converted into a number. The following are some examples of these behaviors:
let result1 = 5 - true; // 4 because true is converted to 1 let result2 = NaN - 1; // NaN let result3 = 5 - 3; // 2 let result4 = 5 - ""; // 5 because "" is converted to 0 let result5 = 5 - "2"; // 3 because "2" is converted to 2 let result6 = 5 - null; // 5 because null is converted to 0