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.

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

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.





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions