i have read this topic already : Explain +var and -var unary operator in javascript
but i still can't understand this simple code :
var a = 3;
console.log(-a); // -3
console.log(+a); // 3
a = -a;
console.log(a); // -3
console.log(+a); // -3
"The unary negation operator precedes its operand and negates it."
"The unary plus operator precedes its operand and evaluates to its operand but attempts to converts it into a number, if it isn't already."
but i still can't figure why console.log(+a) return 3 the first time.
but i still can't figure why console.log(+a) return 3 the first time.
The value of a
is 3
at that point.
The previous line, -a
, takes the value of a
, negates it and passes it to console.log
. It doesn't assign the changed value back to a
.