for...of loop vs for loop over ascending index vs for loop over descending index vs Array#forEach iteration with function vs Array#forEach iteration with arrow function

Edit on GitHub

Compare different ways of iterating an Array instance.

Setup

var arr = [];

for (var i = 0; i < 1000; i++) {
    arr.push(i);
}

Tests

  • for...of loop

    var sum = 0;
    
    for(var i of arr) {
        sum += i;
    }
    if (sum !== 499500) throw new Error('Wrong result');
  • for loop over ascending index

    var sum = 0, len = arr.length;
    
    for(var i = 0; i < len; i++) {
        sum += arr[i];
    }
    if (sum !== 499500) throw new Error('Wrong result');
  • for loop over descending index

    var sum = 0, len = arr.length;
    
    for(var i = len; i--;) {
        sum += arr[i];
    }
    if (sum !== 499500) throw new Error('Wrong result');
  • Array#forEach iteration with function

    var sum = 0;
    
    arr.forEach(function(val) {
        sum += val;
    });
    if (sum !== 499500) throw new Error('Wrong result');
  • Array#forEach iteration with arrow function

    var sum = 0;
    
    arr.forEach(val => sum += val);
    if (sum !== 499500) throw new Error('Wrong result');