DEV Community

Andrew Elans
Andrew Elans

Posted on • Edited on

Array.reduce() in JavaScript

About Array.reduce()

reduce() is a powerful array method. It is considered as an originator of other Array methods like map(), filter(), etc. which can easily be rewritten with reduce().

V8 engine will always try to optimize performance of reduce() as well as any other parts of the javascipt code.

One of the key rules for optimization however is to avoid referencing variables or functions that sit outside the reducer callback function's scope. Otherwise it can create side-effects when reading a non-local variable (i.e. variables outside of a reducer callback function), which will prevent V8 from optimization.

The thisArg argument is not provided for reduce().

This youtube video Comparing JavaScript Array method reduce with for statement demonstrates differences in performance between reduce() and the for statement and explains requirements for the V8 optimization to kick in. Turn on captions and auto-translate.

Examples of reduce()

Real usage scenarious of reduce() will be provided in this blog.

Top comments (0)

This post blew up on DEV in 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay