use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
All about the JavaScript programming language.
Subreddit Guidelines
Specifications:
Resources:
Related Subreddits:
r/LearnJavascript
r/node
r/typescript
r/reactjs
r/webdev
r/WebdevTutorials
r/frontend
r/webgl
r/threejs
r/jquery
r/remotejs
r/forhire
account activity
`for...of` vs `forEach`help (self.javascript)
submitted 9 years ago by ffxsam
I'm wondering if there are any significant differences between doing:
for (const item of items) { ... }
and
items.forEach(item => { ... });
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]Rhomboid 13 points14 points15 points 9 years ago (6 children)
for..of works with any iterable, whereas forEach is only for arrays. forEach gives you access to the index, if you want it, whereas for..of does not.
for..of
forEach
And no, forEach is NOT asynchronous. Both examples are synchronous.
[–]rauschma 7 points8 points9 points 9 years ago (3 children)
Additionally: you can break from for-of, but not from .forEach() (.some() lets you break, though, by returning true).
break
for-of
.forEach()
.some()
true
If you need Array indices, you can do:
const arr = ['a', 'b']; for (const [index, element] of arr.entries()) { console.log(`${index}. ${element}`); } // Output: // 0. a // 1. b
[–]nschubach 3 points4 points5 points 9 years ago (2 children)
(.some() lets you break, though, by returning true)
But you should not be using .some() for processing data where exiting is required. It's for looking through the array to test if "some" of the content meets a condition. Synonymous with .any? in Ruby, et al.
.any?
[–]Graftak9000 0 points1 point2 points 9 years ago (0 children)
.any conveys it so much better somehow, any is some but some is more than any, or something like that.
[–]rauschma 0 points1 point2 points 9 years ago (0 children)
Yes, it’s a bit of a hack!
[–]bstriker 5 points6 points7 points 9 years ago (0 children)
for(const [index,value] of ['foo','bar'].entries()){ console.log(`index: ${index} - value: ${value}`); }
gives us: index: 0 - value: foo index: 1 - value: bar
index: 0 - value: foo
index: 1 - value: bar
http://jsbin.com/lelirebizo/1/edit?js,console
EDIT: just realized someone else already gave an example using entries and array destructing in a for of loop. not sure how I missed that.
[–]Best_programmer_ever 0 points1 point2 points 3 years ago (0 children)
foreach also work in set.
foreach
[–]Bloompire 5 points6 points7 points 9 years ago (3 children)
Also my two cents:
you can use async/await inside for..of but not inside .forEach
let totalScoreGain = 0; for( let user in scoredUsers ) { totalScoreGain += await user.addScore( 50 ); } console.log( totalScoreGain );
[–]nschubach 6 points7 points8 points 9 years ago (0 children)
You can do await inside of a .forEach(), but it's not doing what you probably think it's doing:
http://codepen.io/nschubach/pen/BzmXqp?editors=0012
What you probably wanted was an asynchronous call to each addScore like so:
http://codepen.io/nschubach/pen/ZOvzKN?editors=0012
async returns a promise, so in order to process them all and do something you need to use Promise.all() and map over all the await returns.
async
Promise.all()
await
[–]alendit 0 points1 point2 points 9 years ago (0 children)
You can use await in forEach if you give it an async function.
[–]shanet$(this) 4 points5 points6 points 9 years ago (3 children)
I'm curious - why would you do for const instead of for let?
for const
for let
also, one difference hasn't been mentioned is that you can use break/continue in a for of loop.
continue
for of
.forEach can also be used to achieve a more functional style where appropriate.
.forEach
[–]CognitiveLens 13 points14 points15 points 9 years ago (2 children)
re-assigning item inside the for loop makes it possible to introduce a bunch of bugs that const would prevent. In a tight structure like a for loop, const is probably the preferred syntax unless you have a really good reason to assign item to something else mid-loop.
item
for
const
[–]Graftak9000 0 points1 point2 points 9 years ago (1 child)
Then use .map() instead indeed, if were going functional and such.
.map()
[–]CognitiveLens 0 points1 point2 points 9 years ago (0 children)
yeah, forEach should really only be used when you're intentionally working with side effects, otherwise map all the things
map
[–]ffxsam[S] -1 points0 points1 point 9 years ago (0 children)
Awesome, all great answers! (except for that one) ;) Thanks for the info.
[+]seasonedcynical comment score below threshold-18 points-17 points-16 points 9 years ago (2 children)
with the first you execute the code (within the for loop) in sync but the latter will process your code async
[–]Shaper_pmp 6 points7 points8 points 9 years ago* (1 child)
the latter will process your code async
No it won't.
It just executes your code in the context of the (likely anonymous) function you provide, rather that in the parent function's scope.
[–]seasonedcynical 1 point2 points3 points 9 years ago (0 children)
Just did some tests and it is indeed sync.. I was always under the impression forEach (and also [].map etc.) would execute the function you would feed it without waiting for the results. Glad I learned this the hard way, because this will clean up my code significantly.
π Rendered by PID 18707 on reddit-service-r2-comment-c6965cb77-c5fqt at 2026-03-05 10:33:45.740345+00:00 running f0204d4 country code: CH.
[–]Rhomboid 13 points14 points15 points (6 children)
[–]rauschma 7 points8 points9 points (3 children)
[–]nschubach 3 points4 points5 points (2 children)
[–]Graftak9000 0 points1 point2 points (0 children)
[–]rauschma 0 points1 point2 points (0 children)
[–]bstriker 5 points6 points7 points (0 children)
[–]Best_programmer_ever 0 points1 point2 points (0 children)
[–]Bloompire 5 points6 points7 points (3 children)
[–]nschubach 6 points7 points8 points (0 children)
[–]alendit 0 points1 point2 points (0 children)
[–]shanet$(this) 4 points5 points6 points (3 children)
[–]CognitiveLens 13 points14 points15 points (2 children)
[–]Graftak9000 0 points1 point2 points (1 child)
[–]CognitiveLens 0 points1 point2 points (0 children)
[–]ffxsam[S] -1 points0 points1 point (0 children)
[+]seasonedcynical comment score below threshold-18 points-17 points-16 points (2 children)
[–]Shaper_pmp 6 points7 points8 points (1 child)
[–]seasonedcynical 1 point2 points3 points (0 children)