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.

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

Visualizing Promises and Async/Await 🤯

async await

Learn the ins and outs of Promises and Async/Await!

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay