chaosifier
chaosifier

Reputation: 2964

Why doesn't a post-increment/decrement operator have any effect on a variable inside a loop?

var j = 0;
for( var i = 0; i < 100; i++){
    j = j++;
    console.log(j);
}

The output of the above block of code is 100 zeros instead of numbers from 1 to 100?

j = j + 1; 

The above code on the other hand works as expected. What might be the reason behind this?

Upvotes: 1

Views: 161

Answers (3)

M A
M A

Reputation: 72844

Because it's a post-increment and not a pre-increment. The value of j is first assigned the value zero, then incremented to the new value, which is wasted in the next iteration.

j = j++ translates to:

  1. Load the value of j, which is zero.
  2. Increment j.
  3. Store the loaded value in step 1 to j. Note that the increment in step 2 is lost because its old value was loaded in step 1.

j = ++j translates to:

  1. Increment j.
  2. Load the value of j which is incremented.
  3. Store the loaded value back to j.

Upvotes: 2

Bill the Lizard
Bill the Lizard

Reputation: 405745

j++ loads the current value of j, then increments the variable, then returns the original value.

j = j++ reassigns the original value of j, which is 0, back to j with every iteration of the loop.

If you just put j++; on a line by itself inside the loop you'll see that it does increment.

Upvotes: 6

Avi
Avi

Reputation: 296

You are post incrementing j.At j = j++ value is of j = 0 and it remains 0 as j++ will increment the value after the execution of the statement.You can have just console.log(++j); in for loop.

Upvotes: 1

Related Questions