Javascript - Unary Minus Operator

Introduction

The unary minus operator negates a numeric value, such as converting 1 into -1.

var num = 5; 
num = -num;    //becomes -5 

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:

Value
Boolean values
Number() returns
true and false get converted into 1 and 0, respectively.
numbers
the value is passed through and returned.
null
0
undefined
NaN
strings




If the string contains only numbers, optionally preceded by a plus or minus sign, it is converted to a decimal number, so "1" becomes 1, "123" becomes 123, and "011" becomes 11. leading zeros are ignored.
If the string contains a valid floating-point format, such as "1.1", it is converted into the appropriate floating-point numeric value. Leading zeros are ignored.
If the string contains a valid hexadecimal format, such as "0xf", it is converted into an integer that matches the hexadecimal value.
If the string contains no characters, empty, it is converted to 0.
If the string contains anything other than these previous formats, it is converted into NaN.
objects

valueOf() method is called and the returned value is converted based on the previously described rules.
If that conversion results in NaN, the toString() method is called and the rules for converting strings are applied.

Demo

var s1 = "01"; 
var s2 = "1.1"; 
var s3 = "z"; 
var b = false; //from  w  w w . ja v  a2 s . c om
var f = 1.1; 
var o = {  
    valueOf: function() { 
        return -1; 
    } 
}; 
                    
s1 = -s1;   //value becomes numeric -1 
console.log(s1);
s2 = -s2;   //value becomes numeric -1.1 
console.log(s2);
s3 = -s3;   //value becomes NaN 
console.log(s3);
b = -b;     //value becomes numeric 0 
console.log(b);
f = -f;     //change to -1.1 
console.log(f);
o = -o;     //value becomes numeric 1 
console.log(o);

Result

Related Topic