Gryxs
Gryxs

Reputation: 146

Javascript: Weird behaviour with += operator

I know the title is somewhat vague, but I'm not sure how to really explain this. So, in code

var a= 2, b=3;
a+=b;
//5

This is pretty basic javascript. Now I want to check if the result is larger than a certain number

var a= 2, b=3, c=4;
(a+=b) >= c;
//true

However, if I forget to add the parenthesis, I don't understand where the result could possible come from

var a= 2, b=3, c=4;
a += b >= c;
//2

I tried reading some stuff about order of operations and whatnot, but I still can't understand how that code can possibly output "2"

Upvotes: 3

Views: 65

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074178

Because

a += b >= c;

is

a += (b >= c);

which is (in your case)

a += (false);

which ends up being

a += 0;

which is a.

The right-hand side of all of the assignment operators is evaluated before anything is done with the result. So b >= c is evaluated, giving us false, which is coerced to 0 when you try to treat it as a number with a +=.

Upvotes: 11

Related Questions