Array.reduce() in JavaScript

Andrew Elans - Apr 26 - - Dev Community

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.

. . . . . . . . . . . . . . . .
Terabox Video Player