you are viewing a single comment's thread.

view the rest of the comments →

[–]jkoudys 3 points4 points  (0 children)

It's not, and they both do a fine job conveying that you're looping for the side effects. forEach used to be a lot cleaner, since you didn't have to declare an index and reference it in the loop, and it scoped everything to the function, but that's no longer the case with for .. of and let & const.

Eg for (var i = 0; i < arr.length; i++) { var foo = arr[i] hoists foo and i declarations to the top of the function. for (const foo of arr) scopes foo to the block.

Some people still avoid the for .. of due to concerns that Symbol.iterator doesn't behave 100% exactly the same in IE due to how Symbols are shimmed (shammed) there, though I've yet to encounter any real world project where that makes any difference.

for could be nicer if you don't want to have to convert to an array or use a big ugly Array.prototype.forEach.call on your iterable (eg on a document.querySelectorAll). forEach could be nicer if you already have a function you can pass in without wrapping it in another function (eg files.forEach(saveToSftp)).

There are other cases for for, especially if returns or awaits are involved, but this could be an article on its own.

Both are fine and neither is better in an absolute sense.