JavaScript: Keep it simple! (Part 2)

Sanksshep Mahendra
Nov 3, 2019 · 3 min read

JavaScript is now a more versatile framework than what it used to be. I am excited to write my second article on JavaScript. You can find the first article of this series here —

This article requires you to know the basics of JavaScript, I hope you enjoy reading it.

In this article, we will be discussing .reduce() and how it helps us reduce code 🗜️

.reduce()

.reduce()

.reduce() also runs a callback for each element of an array. .reduce() shares the result of this callback (the accumulator) from one array element to the other.

The accumulator can be anything (integer, string, object, etc.) and should be instantiated or passed when calling .reduce().

Here is an example —

var saleItems = [
{
sku: 00001,
item: 'Vase',
currency:'USD',
price:20
},
{
sku: 00002,
item: 'Pencil',
currency:'USD',
price:10
},
{
sku: 00003,
item: 'Chair',
currency:'USD',
price:100
},
{
sku: 00004,
item: 'Table',
currency:'USD',
price:500
},
{
sku: 00005,
item: 'Lamp',
currency:'USD',
price:350
},
{
sku: 00006,
item: 'Box',
currency:'USD',
price:50
}
];

We need to know the total price of all the sale items. With .reduce(), it’s simple compared to .forEach(), .for(...of), or .for():

var totalPrice = saleItems.reduce(function (accumulator, list) {
return accumulator + list.price;
}, 0);

Can we reduce this to one line of code? (pun intended) 😜

const totalPrice = saleItems.reduce((acc, list) => acc + list.price, 0);

Can .reduce() be used to find out the most expensive product?

var mostExpProduct = saleItems.reduce(function (expensive, list) {
return (expensive.price || 0) > list.price ? expensive : list;
}, {});

Our accumulator is expensive in this case.

Easy to test —

Provide inbound data for the function and results should come out. It leads to less manipulation. It’s straightforward, simple testing.

Performance benefits —

Conclusion -

I hope this helps you! if you liked reading this, you may also like —

JavaScript in Plain English

Learn the web's most important programming language.

Sanksshep Mahendra

Written by

I am a technology executive with success driving the strategy, design, and execution of software engineering with AI and ML.

JavaScript in Plain English

Learn the web's most important programming language.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade