Javascript for beginners — Understanding the reduce function.

Photo by Christopher Gower on Unsplash

Working as a frontend developer, you will eventually stumble upon the reduce function. A built in method that is executing a reducer function on each element of an array which will result in 1 single output value.

The name Reducer can be a confusing word to begin with. We can’t at first sight associate the name to a real world example like for example the filter method. It should just be understood as reducing a collection of items into a single value. That’s it.

The word reducer is a commonly known term from functional programming languages like F# which Javascript has adopted some higher order functions from along with map and filter.

Trying to explain the reduce function in simple terms. You have a collection of items and you want to “reduce” it into a single value. Every time we are reducing the collection we use a “reducer”.

Let’s say we have a collection consisting of 6 characters like my name “Kasper”.

const name = ['K', 'A', 'S', 'P', 'E', 'R'];

Our job as a developer is to concat all the characters into a string which we can pass to a variable or object we later need. The issue is that all the characters is in uppercase, but we want them to be in lowercase, therefore we cannot use the Array.prototype.join method.

One way is to map over each item in the array, convert it to lowercase letter and then append to an empty string, but then we are relying on variable outside the method, which does not make it a pure function.

The reduce function makes this quit simple.

const name = ['K', 'A', 'S', 'P', 'E', 'R'];
const toLowerCaseNameReducer = (accumulator, value) => accumulator += value.toLowerCase();
const newName = name.reduce(toLowerCaseNameReducer, "");

Here we pass the toLowerCaseNameReducer to the reduce function, and set the initial value to be an empty string. The reducer function has 2 parameters. 1 parameter is the accumulator.

The accumulator contains the accumulated values, which means every time we are iterating over the array, the accumulator keeps building up the string with new characters from each iteration. First iteration the accumulator is empty and then we add the value K to the string after we have turned it into a lowercase k.
Next iteration we take the existing accumulator k and add the value a to it. Third iteration we take the value s and append it to ka. and so forth until we have iterated over all the elements and will return the accumulating value which is kasper.

Another example is when you want to sum the values in an array. You can easily do that with the reduce method to.

const differentAges = [10, 4, 2, 1, 4, 5];
const sumAge = differentAges.reduce((acc, val) => acc += val, 0);

Here you should be aware of the initial value. In this example 0 is the initial value since the initial age is 0. If we provided a string, then we will keep appending a number to a string, which will result in the value “1042145” instead of 26.

The third parameter of the reduce function is the index and the fourth parameter is the array itself in case you need access the reducing array or the index.




Senior Frontend Developer at EazyProject A/S

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Creating a Landing Page Using TUK Components

Regex / Regular expressions and XPaths alternatives every SEO needs

🔰 Ansible Playbook which will dynamically load the variable file named same as OS_name and just…

Building a multi-language, printable coronavirus safety card

Stop using Array.forEach for everything! “for/of”, USE IT!

Pink No Sweat$: A 3D Music Game Made Easy With Anything World

JavaScript: How is callback execution strategy for promises different than DOM events callback?

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Kasper Due

Kasper Due

Senior Frontend Developer at EazyProject A/S

More from Medium

How to use Reduce in JavaScript

Revelations: How JavaScript Works Behind The Scenes

Map, filter and reduce - JavaScript. Understand and accept.

Dynamic Typing and coercion in Javascript