Kayote
Kayote

Reputation: 15647

Confusion About Operator Precedence

Im going through the 'Grammer' chapter in Kyle's You Dont Know Js.

As per this link at MDN, ...++ Postfix increment has a higher precedence over = & even ++... Prefix increment. Yet, in javascript, the following code seems to prove otherwise.

var a = 1;
var b = a++; // b = 1; a = 2;
var c = ++a; // c = 3; a = 3;

What am I getting wrong? Doesn't the above code show that = & ...++ Postfix increment have a higher precedence over = & ++...?

Upvotes: 0

Views: 53

Answers (1)

Bogdan
Bogdan

Reputation: 126

The order of evaluation is (from high precedence to low): postfix operator a++, prefix operator ++a, addition operator + (from left-to-right), and the assignment operator =, from MDN.

Take a look at the following:

var a = 1;
var b = a++ + ++a + a++;
// The order is:
// b = 1 + ++a + a++;
// b = 1 + ++a + 2;
// b = 1 + 4 + 2;
// b = 7; a = 4;

The order of evaluation is maintained, just that the postfix operator increments the value of a after the last operation has finished, i.e. the assignment operator.

Upvotes: 1

Related Questions