DEV Community

Aman Kumar
Aman Kumar

Posted on

# ๐Ÿงฎ Crushing Numbers with `.reduce()` in JavaScript: From Totals to Real-Life Scenarios

๐Ÿง  What is .reduce()?

.reduce() is a method that reduces an array to a single value by applying a function on each element โ€” one at a time โ€” while keeping track of an accumulator.

Letโ€™s see it in action:


๐Ÿ” Basic Example: Adding Numbers in an Array

const myNums = [1, 2, 3, 4, 5];

const myTotal = myNums.reduce(function (acc, currVal) {
    console.log(`acc: ${acc} and currval: ${currVal}`);
    return acc + currVal;
}, 0); // 0 is the initial value of the accumulator

console.log(myTotal);
Enter fullscreen mode Exit fullscreen mode

๐Ÿงพ Output:

acc: 0 and currval: 1
acc: 1 and currval: 2
acc: 3 and currval: 3
acc: 6 and currval: 4
acc: 10 and currval: 5
15
Enter fullscreen mode Exit fullscreen mode

๐Ÿ” acc keeps track of the total so far, and currVal is the current item from the array.


โœ… Arrow Function Version

const NewTotal = myNums.reduce((acc, curr) => acc + curr, 0);
console.log(NewTotal);
Enter fullscreen mode Exit fullscreen mode

โœ”๏ธ Cleaner and more readable for simple operations.


๐Ÿ›’ Real-Life Use Case: Calculating Total Price in a Cart

Imagine you're building an e-commerce site, and you want to calculate the total price from the cart. Here's how:

const shoppingCart = [
    { itemName: "JS Course", price: 2999 },
    { itemName: "Py Course", price: 999 },
    { itemName: "Mobile dev Course", price: 5999 },
    { itemName: "Data Science Course", price: 12999 },
];

const priceToPay = shoppingCart.reduce((acc, item) => acc + item.price, 0);

console.log(priceToPay); // Output: 22996
Enter fullscreen mode Exit fullscreen mode

๐Ÿ›๏ธ Instead of manually looping and adding, reduce() elegantly combines it all into one line.


๐Ÿ“Œ Syntax Recap

array.reduce((accumulator, currentValue) => {
    // logic
    return updatedAccumulator;
}, initialValue);
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”„ .reduce() vs .map() or .filter()

Method Purpose Returns
.map() Transforms each item New array
.filter() Selects items based on condition New array
.reduce() Combines all items into one result Single value

๐Ÿง  Final Takeaway

.reduce() is powerful and versatile โ€” from summing numbers to aggregating complex data. Once you get the hang of it, youโ€™ll start reaching for it every time you need to calculate a total, build a string, or even transform arrays in advanced ways.


Top comments (0)