A Deep Dive into JavaScript's Higher-order functions.( map, forEach, filter, and reduce)

A Deep Dive into JavaScript's Higher-order functions.( map, forEach, filter, and reduce)

Welcome to the Dynamic World of JavaScript, where Coding Possibilities Unfold at Every Turn!

Overview

In our last piece, we talked about higher-order functions, a Beginner's Guide covering the basics of functions, their importance, and the benefits of higher-order functions. We explained what functions are and why higher-order functions matter. If you missed that, you can catch up Here. Now, we're taking a closer look at higher-order functions, digging into the details of built-in Higher-order Functions.

Introduction

Today, as we continue our journey through the exciting landscapes of JavaScript, we venture into a concept that might sound complex at first but harbors extraordinary power, especially for those taking their initial steps into the coding universe. In this second installment, we're unraveling the magic behind JavaScript's built-in higher-order functions which include map, filter, forEach, and reduce. Get ready for a journey that not only makes complex things simpler but also unlocks a whole world of coding possibilities. Excited to dive into the core of JavaScript's functional power? Let's start this learning adventure together! 🚀✨

What is a map() function?

In JavaScript, the map() function is a higher-order function that is used to iterate over an array and apply a function to each element in the array. It creates a new array with the results of calling a provided function on every element in the array. Note that the original array remains unchanged. Under the hood, map() passes three arguments to your callback:

  • the current item in the array.

  • the array index of the current item.

  • the entire array you called map() on.

For example, we have an array of numbers, and we want to create a new array that will contain every element in the first array multiplied by five. Let’s solve the problem with and without a higher-order function.

Using a Normal Loop

Here’s how we can solve the problem using a normal function.

const num = [10, 20, 30];
const num5 = [];
for(let i = 0; i < num.length; i++) {
  num5.push(num[i] * 5);
}

console.log(num5);
// prints [ 50, 100, 150 ]

Using a Higher-Order function (Map)

Here’s how we can solve the same problem using a Higher-Order Function (Map).

const num = [10, 20, 30];
const num5 = num.map(i => i * 5);
console.log(num5);
// prints [ 50, 100, 150 ]

Here we did not include the index and array parameters, this is to remind you that they're there if you need them. Since we didn't use them here, though, you could add them, and the code would run just fine.

From the above map function, you can see that we can achieve the same output with less code and better structure. So, let us move to the next built-in function.

What is a forEach() function?

The forEach() method is a built-in JavaScript array method that is used to iterate over the elements of an array. It executes a provided function once for each array element, in ascending order. Unlike some other array methods (such as map() or filter()), forEach() does not create a new array. Instead, it is used for performing a specific action on each element of the existing array.

forEach() passes the following arguments to your callback:

  • The array to iterate over

  • The current element being processed in the array.

  • The index of the current element being processed (optional).

  • the entire array you called forEach() on (optional).

For example, let's say you have an array of users, and you want to log a personalized greeting for each user using the forEach()

The code will look like:

const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' },
];

// Using forEach to log personalized greetings
users.forEach(user => {
  console.log(`Hello, ${user.name}! Your user ID is ${user.id}.`);
});

//Hello, Alice! Your user ID is 1.
//Hello, Bob! Your user ID is 2.
//Hello, Charlie! Your user ID is 3.

What is a filter() function?

In JavaScript, the filter() function is a higher-order function that is used to create a new array containing only the elements of the original array that satisfy a specified condition. Here the original array remains unchanged. Just like the map() function, the filter() function iterates over an array checking which values satisfy a specific condition. Also, filter() passes three arguments to your callback:

  • the current item in the array.

  • the array index of the current item.

  • the entire array you called filter() on.

For example, let’s say we have an array containing objects of bank accounts with accounts type either current or savings, and we need to filter the array to get all savings accounts.

First let's write the data:

const bankAccounts = [
  { accountType: 'savings', balance: 5000, name: 'John James' },
  { accountType: 'current', balance: 10000, name: 'Micheal Obi', },
  { accountType: 'savings', balance: 7500, name: 'Bola Ade' },
  { accountType: 'current', balance: 12000, name: 'Emmanuel John' },
  { accountType: 'savings', balance: 9000, name: 'Faithfulness Alamu'},
];

Here’s how we can solve the problem using a normal loop.

// Using for loop
const savingsAccountsForLoop = [];

for (let i = 0; i < bankAccounts.length; i++) {
  if (bankAccounts[i].accountType === 'savings') {
    savingsAccountsForLoop.push(bankAccounts[i]);
  }
}

console.log(savingsAccountsForLoop);

/*
[
 { accountType: 'savings', balance: 5000, name: 'John James' },
 { accountType: 'savings', balance: 7500, name: 'Bola Ade' },
 { accountType: 'savings', balance: 9000, name: 'Faithfulness Alamu'},
]
*/

Using a Higher-Order Function (Filter)

// Using filter
const savingsAccountsFilter = bankAccounts.filter(account => account.accountType === 'savings');
console.log(savingsAccountsFilter);
/*
[
 { accountType: 'savings', balance: 5000, name: 'John James' },
 { accountType: 'savings', balance: 7500, name: 'Bola Ade' },
 { accountType: 'savings', balance: 9000, name: 'Faithfulness Alamu'},
]
*/

Just like the map() function, we did not include the index and array parameters, this is to remind you that they're there if you need them.

The filter() method provides a more concise and expressive way to solve this task.

What is a reduce() function?

The reduce() function is another higher-order function that is used to reduce an array to a single value. It iterates over each element of the array, applying a provided callback function and accumulating the result. The callback function takes four arguments:

  • an accumulator

  • the current element

  • the current index

  • the original array.

For example, Let's say you want to find the sum of a list of numbers.

Here’s how we can solve the problem using a normal function.

const numbers = [10, 29, 11, 43, 37];
let total = 0;
for(let i = 0; i < numbers.length; i++) {
  total = total + numbers[i];
}
console.log(total); // prints 130

Using a reduce() function,

const numbers = [10, 29, 11, 43, 37];
const total = numbers.reduce((acc, curr) => {
  return acc + curr
}, 0)
console.log(total)
//Prints 130

//####### Note ###########
//the zero is the initial value 
//if it changes to 20 we will have 150 as our answer meaning
// that we will add 20 + 10 + +29 + 11 + 43 +37

Let us take another example.

Imagine you have a shopping cart with various items, each tagged with its respective price. How would you calculate the total amount for all the items in your shopping cart?

Calculating total amount using reduce().


const shoppingCart = [
  { item: 'Product A', price: 20.99 },
  { item: 'Product B', price: 15.49 },
  { item: 'Product C', price: 10.99 },
  // ... other items
]
const totalAmount = shoppingCart.reduce((accumulator, currentItem) => {
  return accumulator + currentItem.price
}, 0)

console.log(
  `Total amount for items in the shopping cart: $${totalAmount.toFixed(2)}`
)
//Total amount for items in the shopping cart: $47.47

In this example, the reduce() method iterates through the shoppingCart array, and for each item, it adds the item's price to the accumulator. The initial value of the accumulator is set to 0. The final result, totalAmount, is the sum of prices for all items in the shopping cart.

Summary

The map() function creates a new array by transforming every element in an array individually. The filter() function creates a new array by removing elements that do not satisfy the specified condition. The forEach() function does not create a new array. Instead, it is used for performing a specific action on each element of the existing array. Finally, the reduce() function takes all of the elements in an array and reduces them into a single value.

Get ready for an exciting dive into the world of Arrays where we will work with some built-in Higher-Order Functions like map, filter, forEach, and reduce and also work with some array methods such as sort, pop, slice, splice, etc. in my upcoming article! 🚀 Stay tuned for a coding adventure and let's make programming an absolute delight! 🌈🌟 Happy coding! 🎉.

Follow me!!!

Linkedin

Github

twitter