Lone Learner
Lone Learner

Reputation: 20638

Modifying a variable more than once in a statement and order of evaluation of function arguments in JavaScript

How do we reason about these JavaScript statements and explain their output?

  1. i = 1; i = i++; console.log(i); // Outputs 1 in Firefox
  2. i = 1; x = i++ + i++; console.log(i, x); // Outputs 3 3 in Firefox
  3. i = 1; console.log(i, i++); // Outputs 1 1 in Firefox

In C, the equivalent statements for (1) and (2) would be said to invoke undefined behavior because we are modifying the value of i more than once between two sequence points. In C, the equivalent statement for (3) would be said to invoke undefined behavior because the order of evaluation of function arguments is undefined. What are the rules in JavaScript?

Upvotes: 1

Views: 64

Answers (1)

thefourtheye
thefourtheye

Reputation: 239503

As per the ECMA 5.1 Specification of Postfix Increment Operator,

  1. Let lhs be the result of evaluating LeftHandSideExpression.
  2. Let oldValue be ToNumber(GetValue(lhs)).
  3. Let newValue be the result of adding the value 1 to oldValue, using the same rules as for the + operator (see 11.6.3).
  4. Call PutValue(lhs, newValue).
  5. Return oldValue.

As per the rules, lets evaluate the expressions

i = i++

The value will be incremented and set in i. as per step 4 and 5. Then the oldValue 1 itself is returned and you are storing it again in i. That is why you are getting 1.

x = i++ + i++

The same logic. i++ evaluates to 1 and i is set to 2. Now, the next i++ is evaluated which evaluates to 2 and the value of i is set to 3. So the sum of 1 and 2 is assigned to x. That is why it prints 3 3

console.log(i, i++)

Again, the same logic. i is 1 and i++ evaluates to 1, but the value is set to 2 only. That is why it prints 1 1

Upvotes: 2

Related Questions