Reputation: 2964
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
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:
j
, which is zero.j
.j
. Note that the increment in step 2 is lost because its old value was loaded in step 1.j = ++j
translates to:
j
.j
which is incremented.j
.Upvotes: 2
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
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