-5

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.

Community
  • 1
  • 1
seb_kaine
  • 149
  • 8

1 Answers1

4

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Thanks Quentin so ++ and + doesn't behave the same way in js. Because if i make var a = 0; console.log(++a); // 1 console.log(--a); // 0. so in that case having the operator before the operand does modify the variable. In other word when the operator ++ is before it modify the variable, but the when the operator + is before it doesn't modify it ? Js is tricky ... :) – seb_kaine Sep 08 '15 at 15:23
  • `++a` is short for `a = a+1` – Barmar Sep 08 '15 at 15:27
  • Well, yes. Different operators do different things. – Quentin Sep 08 '15 at 15:27
  • `+a` and `++a` are totally different. – Barmar Sep 08 '15 at 15:27
  • thanks guys for your answers. and forgive the noobish question. – seb_kaine Sep 08 '15 at 15:29