Javascript Arithmetic Operator Unary Plus and Minus

Introduction

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

let num = 25; /*www  . ja va 2s .c  o m*/
num = +num; 
console.log(num);  // 25 

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

  • Boolean values of false and true are converted to 0 and 1
  • string values are parsed according to a set of specific rules
  • objects have their valueOf() and/or toString() method called to get a value to convert.

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

let s1 = "01"; 
let s2 = "1.1"; 
let s3 = "z"; 
let b = false; /* w w  w . ja  v a2 s .c  om*/
let f = 1.1; 
let o = {  
  valueOf() { 
    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;    // no change, still 1.1 
console.log(f);
o = +o;    // value becomes numeric -1 
console.log(o);

The unary minus operator's primary use is to negate a numeric value, such as converting 1 into -1.

The simple case is illustrated here:

let num = 25; //from  w w w  .j a v a 2s .  c o  m
num = -num; 
console.log(num);  // -25 

When used on a numeric value, the unary minus negates the value.

When used on nonnumeric values, unary minus applies all of the same rules as unary plus and then negates the result:

let s1 = "01"; 
let s2 = "1.1"; 
let s3 = "z"; 
let b = false; /*from   w ww  . j  a  v a  2s. co m*/
let f = 1.1; 
let o = {  
  valueOf() { 
    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);

The unary plus and minus operators are used primarily for basic arithmetic but can also be useful for conversion purposes.




PreviousNext

Related