DEV Community

Cover image for How to use Reduce in javascript?
Valentin Antonio
Valentin Antonio

Posted on

3 1

How to use Reduce in javascript?

The reduce() method is used to apply a function to each element in the array to reduce the array to a single value.

Example:


const ages = [33,12,20,16,5,54,21,44,23,55,45,90];

let ageSum = 0;

for(let i=0; i < ages.length; i++){
     ageSum += ages[i];
  }
//result
console.log(ageSum);
// 418

The method:

const ageSum = ages.reduce((total,age) => total + age ,0);
//result
console.log(ageSum);
// 418

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs