Are there any cases JavaScript’s forEach works where a for loop doesn’t?

Viewed 170

JavaScript’s Array.prototype.forEach is usually significantly slower than a for loop. This is because forEach includes extra checks that a for loop normally doesn’t have. Are there any cases where a forEach loop works (because of these checks) where a for loop doesn’t?

To be clear, I am not asking why for is faster than forEach. I am asking if the extra checks in forEach are ever useful.

3 Answers

forEach() skip empty elements (holes) in the array, for do not.

You could make the for loop as slow as you want by changing the traditional increment to a more complex operation. It also has to do an inequality check during each iteration, so that is another opportunity to introduce delays, by using a more complex condition.

forEach is very specific, but for can offer more flexibility.

Related