0

Here is an array example:

var arr = [0,1,2,3];

Is this code ...

for(var i = 0, l = arr.length; i < l; i++ ){
    sum += arr[i];
}

equivalent to this code ...

arr.forEach(function(val)){
    sum += val;
}

I would guess that they are functionally the same but one has better performance?

If so I would assume forEach is preferred as it is "cleaner", but a raw loop has better performance.

  • No, they're not the same. Why guess? Read the docs. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach –  Mar 08 '17 at 00:29
  • performance should be at the bottom of a list of criteria in 99% of cases – dandavis Mar 08 '17 at 00:33
  • `forEach` is never cleaner. If you want clean and functional code, use `reduce`; if you want clean and imperative code use `for … of` – Bergi Mar 08 '17 at 02:15

0 Answers0