js Intermediate
Sum using reduce
Open this example in our interactive code editor to experiment with it.
Try the EditorSum those numbers
const numbers = [5, 10, 15, 20];
const sum = numbers.reduce((acc, value) => acc += value, 0);
Summary
.reduce()is one of the most versatile array methods in JavaScript. It iterates over every element and accumulates a single result based on the callback function you provide.- The callback receives an accumulator (
acc) and the current value. The accumulator carries the running total, and0is the initial value passed as the second argument to.reduce(). - Beyond summing numbers,
.reduce()can be used to calculate averages, flatten arrays, group data, and build entirely new data structures. - It also works with strings and objects, making it a powerful tool for transforming arrays into any shape you need.
Try this in our interactive code editor
Practice hands-on with our built-in code sandbox.
Open Code Editor
Adrian Bigaj
Creator of BigDevSoon
Full-stack developer and educator passionate about helping developers build real-world skills through hands-on projects. Creator of BigDevSoon, a vibe coding platform with 21 projects, 100 coding challenges, 40+ practice problems, and Merlin AI.
Related Pills
js Intermediate
JavaScript multiple condition checks
Checking multiple values in JavaScript often leads to redundant, boilerplate code - let's use .includes method to fix that.
js Intermediate
Convert JavaScript data structures
Converting data structures is a day-to-day job as a Developer.
js Intermediate
ECMAScript new features
Null coalescing operator, optional chaining, and Array.flat method are all amazing.