How to use Reduce | JavaScript

/ #JavaScript


JavaScript Reduce is a Higher-Order function and in this post I'll show you how to use it.

What is a Higher-Order function?

A higher order function is a function that operates on other functions. They can either take functions as arguments, or they can return them. In other words, either you pass inn a function or you get a function in return.

A quick example

The reduce function accepts two parameters. The reducer function (callback) and an optional inital value. Let's say we have a list of numbers and we want to get the sum of all of them. Without reduce, it would look something like this:

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

let sum = 0;

for (let i = 0; i < arr.length; i++) {
	sum = sum + arr[i];
}

// Print the array

console.log(sum);

// Will return
// 15

But since we have a higher-order function for this purpose, it can look much simpler:

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

const sum = arr.reduce(function(accumulator, currentValue) {
	return accumulator + currentValue;
});

// Print the array

console.log(sum);

// Will return
// 15

Questions?

If any of this was unclear, feel free to leave me a reply below!

Comments

No comments yet...

Add comment

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.