Javascript - Unary Plus Operator

Introduction

The unary plus is represented by a single plus sign (+) placed before a variable and does nothing to a numeric value:

var num = 5; 
num = +num;    //still 5 

When the unary plus is applied to a nonnumeric value, it performs the same conversion as the Number() casting function:

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.

The following example demonstrates the behavior of the unary plus when acting on different data types:

Demo

var s1 = "02"; 
var s2 = "1.1"; 
var s3 = "asdf"; 
var s4 = false; /* w w w  .j  av  a  2  s  .c om*/
var s5 = 1.1; 
var o = {  
    valueOf: function() { 
        return -1; 
    } 
}; 
                    
s1 = +s1;   //value becomes numeric 2 
console.log(s1);
s2 = +s2;   //value becomes numeric 1.1 
console.log(s2);
s3 = +s3;   //value becomes NaN 
console.log(s3);
s4 = +s4;     //value becomes numeric 0 
console.log(s4);
s5 = +s5;     //no change, still 1.1 
console.log(s5);
o = +o;     //value becomes numeric -1 
console.log(o);

Result

Related Topic