3

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"

1

1 Answer 1

11

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 +=.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.