JavaScript is a super versatile language. I love it and it really has come a long way over recent years. With JavaScript, we can now build powerful...
For further actions, you may consider blocking this person and/or reporting abuse
Mine would probably be
map()
,sort()
andfilter()
, with an honourable mention forreduce()
.Because I use React a lot, I often have to loop through a list of sub components to render. For that,
map()
is indispensable in transforming an array from a list of Javascript objects into React components. It's also common to have to sort and filter them.On occasion I also need to produce some form of aggregate from array data, and the combination of
map()
andreduce()
can be very powerful for that.+1 for
map
. It's a really great and clean method to transform array data structures. Use it all the time, no matter if it's a React component or a vanilla javascript.The forEach has come up a lot. I'll throw a reminder in here of its performance hit (minor) and more-so, something people might not know is that the forEach is not truly Iterable... hence, continue and break statements don't work. Knowing that tidbit can determine when and when not to use the forEach.
The reason why people would use a for loop over a foreach loop is for speed. For loops perform much faster than a foreach
Unless you are looping over massive arrays, it doesn't really matter in my opinion. I'd much value readability over a couple of milliseconds. If it proved to be a performance issue in the grand scheme of things it could always be replaced with a for loop.
Agreed, I'll almost always opt for
forEach
. Thoughfor
allows you to break out early, which is nice when needed.Actually this is also possible with
forEach
, since a function is called for each element. just do areturn
EDIT: This was a misunderstanding of the desired behavior. Using return will just skip the current element and continue with the rest of the array, see my comment below
You sure about that? AFAIK
forEach
will continue to run until the end of the array.jsfiddle.net/jamesbrndwgn/mz0ynkvb/
Unless there's some trick I'm not aware of?
Ah I'm sorry I understood you wrong. I thought you meant skipping an element like continue. You meant completely stop after a certain element. This is currently not possible with
forEach
, but you could usefor (obj of array)
orsome
instead to achieve that behaviorSorry again for the misunderstanding