Explain +var and -var unary operator in javascript

余生长醉 提交于 2019-11-26 19:01:25

The + operator doesn't change the sign of the value, and the - operator does change the sign. The outcome of both operators depend on the sign of the original value, neither operator makes the value positive or negative regardless of the original sign.

var a = 4;
a = -a; // -4
a = +a; // -4

The abs function does what you think that the + opreator does; it makes the value positive regardless of the original sign.

var a =-4;
a = Math.abs(a); // 4

Doing +a is practically the same as doing a * 1; it converts the value in a to a number if needed, but after that it doesn't change the value.

var a = "5";
a = +a; // 5

The + operator is used sometimes to convert string to numbers, but you have the parseInt and parseFloat functions for doing the conversion in a more specific way.

var a = "5";
a = parseInt(a, 10); //5

One example is that they can be used to convert a string to a number,

var threeStr = '3.0'
var three = +threeStr
console.log(threeStr + 3) // '3.03'
console.log(three + 3) //6

I would like to explain this from basic mathematical point:
The multiplying rules:

Positive x Positive = Positive: 3 x 2 = 6  
Negative x Negative = Positive: (-2) x (-8) = 16   
Negative x Positive = Negative: (-3) x 4 = -12  
Positive x Negative = Negative: 3 x (-4) = -12  

Considering you example:

a = -10;
a = +a
document.writeln(a);

+a = +(-10) = Positive x Negative = Negative = -10

a = false;
a = +a;
document.writeln(a);

false == 0, +a = +(+0) = Positive * Positive = Positive = 0 (maybe use true is a better example)

a = 1
b = -a
console.log(b)

output
-1

Try this

false == 0 // returns true

So,

a = false

a = +a //a * 1

console.log(a) // prints 0 as expected

'+' operator in a variable 'a' simply means : a

'-' operator in a variable 'a' simply means : -a

Since, in above example 
a=-10;
a= +a; // means a, ie, +(-10) which is -10

but,
a= -a;  // means -a, ie, -(-10) which is +10

+a means a*1 and -a means a*(-1)

Thats it!!!!!!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!