How to use Unary Plus in Javascript
Description
The unary plus is represented by a single plus sign (+) placed before a variable and does nothing to a numeric value.
var num = 25;
console.log(num);
num = +num; //still 25
console.log(num);
The code above generates the following result.
Conversion
When the unary plus is applied to a nonnumeric value, it performs the same conversion as the Number() casting function:
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
The following example demonstrates the behavior of the unary plus when acting on different data types:
var s1 = "02";
var s2 = "1.2";
var s3 = "b";
var b = false;
var f = 1.1;
var o = {
valueOf: function() {//from w w w . j a va 2s . c o 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.