3

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?

ciso
  • 2,887
  • 6
  • 33
  • 58

1 Answers1

15

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.

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • 5
    Additionally, some background-information, why there's people who use `++index` to increment a variable: There might be a performance difference between `index++` and `++index` in *compiled* languages as the compiler can transform the latter to fewer machine instructions. However in Javascript this is no such difference (and modern compilers should be able to detect if you're not accessing the variable and optimize it anyway). – t.animal Feb 28 '14 at 02:02
  • 2
    Thank you, p.s.w.g. You answered another one of my questions very clearly previously. I appreciate your help very much. As I get more skilled I hope to help others one day soon like you've helped me. – ciso Feb 28 '14 at 02:03
  • He/She answered it from my perspective. No difference in outcome. The loop and function will do exactly the same thing with my change. I did find this immaterial performance difference though http://jsperf.com/i-vs-i/2 in another post but it makes no difference to the outcome. – ciso Feb 28 '14 at 02:51
  • @p.s.w.g—cool. I have no idea why Crockford prefers `i+=1` to `i++` but I guess I can't start that discussion here… :-) – RobG Feb 28 '14 at 06:15