Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between ++i and i++ in this loop?

The array.prototype.reduce function at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

It has the following loop:

for (index = 0; length > index; ++index) {
    if (this.hasOwnProperty(index)) {
      if (isValueSet) {
         value = callback(value, this[index], index, this);
      } else {
        value = this[index];
        isValueSet = true;
      }
    }
}

I don't think there is a difference whether the index is pre or post incremented here since it's done after the loop iterates each time, but want to be certain.

Can this be changed to index += 1 so it passes jslint? Please don't debate the merits of jslint's warning.

Would this change make any difference?


1 Answers

The only difference between i++, ++i, and i += 1 is the value that's returned from the expression. Consider the following:

// Case 1:
var i = 0, r = i++;
console.log(i, r); // 1, 0

// Case 2:
var i = 0, r = ++i;
console.log(i, r); // 1, 1

// Case 3:
var i = 0, r = (i += 1);
console.log(i, r); // 1, 1

In these cases, i remains the same after the increment, but r is different, i += 1 just being a slightly more verbose form of ++i.

In your code, you're not using the return value at all, so no, there is no difference. Personally, I prefer to use i++ unless there is a specific need to use one of the other forms.

like image 181
p.s.w.g Avatar answered Dec 07 '25 21:12

p.s.w.g



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!