Javascript: Why you should use for() to iterate

We did a comparison of operations per second using Array.forEach and for().

Iteration in javascript performance

In red: using for() In blue: using forEach

Chrome 48 gave us the following performance:

  • using the for(): 63000 ops/sec
  • using the forEach(): 1700000 ops/sec

The higher the better since it means more operations per second.

The code executed was:

elements.forEach(function (item) {
    console.log(item);
})
for (var i = 0, len = elements.length; i < len; i++) {
      console.log(elements[i]);
}