How to use Unary Minus in Javascript
Description
The unary minus is represented by a single minus sign (-) placed before a variable.
Its primary use is to negate a numeric value
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.
Parameter | Number Function Returns |
---|---|
Boolean true | 1 |
Boolean false | 0 |
null | 0 |
undefined | NaN |
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 |
objects | the valueOf() method is called and the returned value is converted |
Example
var s1 = "02";
var s2 = "1.2";
var s3 = "b";
var b = false;
var f = 1.1;
var o = {
valueOf: function() {/*from ww w . j av a 2 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.