DEV Community

Discussion on: Why you should use Array.some instead of 'for' loop or forEach?

Collapse
 
sannajammeh5 profile image
Sanna Jammeh

Behind the scenes V8 does not compile forEach, map, reduce etc to a for loop and then executes. It has its very own implementation within the runtime at the lowest possible level.

Only for polyfills where the engine does not have an implementation will you see a behind the scenes "for" or "while" loop.

Thread Thread
 
mazentouati profile image
Mazen Touati

Thank you for bringing this up. Indeed, V8 pre-compiles it to bytecode to enhance performance and to optimize memory usage. My comment made it sound like they're some kind of a library written in JS and being imported to your code to add new functions to the Array's protytpe. That's what I was thinking to be honest. After checking, it turns out V8 uses its own language V8 Torque and pre-compiles it to bytecode. Here's Array.some source code for example.

However, what I've tried to say is that it has to loop through the items at some point (even in the lowest level). Also, These optimations are not exclusive to the built-in functions. V8 will optimize your code too. For instance, most of the benchmarks I've consulted state that native for loops are faster than forEach, reduce, map etc.

The whole point was to point out that using For loops is not a wrong approach unlike what's being said in this Article.