DEV Community

Cover image for πŸš€ Higher Order Functions in JavaScript: Let's Dive In!
Jagroop Singh
Jagroop Singh

Posted on

πŸš€ Higher Order Functions in JavaScript: Let's Dive In!

JavaScript has a lot of tricks up its sleeve, and higher-order functions (HOFs) are one of the coolest. Whether you're wrangling data, building UIs, or crafting algorithms, HOFs will be your best friend. So, what are they? πŸ€”

A higher-order function is a function that either:

  1. Takes another function as an argument.
  2. Returns a function.

Simple, right? Now, let's cut the theory and dive into some juicy examples! πŸ”₯


1️⃣ Passing Functions as Arguments

Let's say you want to apply a function to every item in an array. That's where .map() steps in, one of JavaScript's higher-order champions.

Example:

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

// HOF: Using map to double each number
const doubled = numbers.map(num => num * 2);

console.log(doubled); // [2, 4, 6, 8, 10]
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ How it works:

  • .map() accepts a function (num => num * 2) as its argument.
  • It applies that function to every item in the array.

2️⃣ Functions That Return Functions

Sometimes, a function needs to build another function dynamically. 🀯

Currying is a classic example!

Example:

const multiplyBy = multiplier => number => number * multiplier;

// Create specific multiplier functions
const double = multiplyBy(2);
const triple = multiplyBy(3);

console.log(double(5)); // 10
console.log(triple(5)); // 15
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Why?

This allows you to create flexible, reusable logic. You write the logic once and generate custom functions on the fly. πŸš€


3️⃣ Filtering Made Fun

Another HOF hero is .filter(). It lets you cherry-pick items from an array based on a condition.

Example:

const words = ["apple", "banana", "kiwi", "apricot"];

// HOF: Filter words starting with 'a'
const startsWithA = words.filter(word => word.startsWith("a"));

console.log(startsWithA); // ["apple", "apricot"]
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Pro tip: Combine .map() and .filter() to chain operations like a pro.


4️⃣ Reduce Your Problems

.reduce() is a jack-of-all-trades. It processes an array and boils it down to a single value.

Example:

const prices = [10, 20, 30];

// HOF: Calculate the total sum
const total = prices.reduce((sum, price) => sum + price, 0);

console.log(total); // 60
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Use case: From summing values to flattening arrays, .reduce() is your go-to tool.


5️⃣ Bonus: Callbacks & Event Listeners

Functions like addEventListener are also higher-order functions because they take callbacks as arguments.

Example:

document.querySelector("button").addEventListener("click", () => {
  console.log("Button clicked! πŸš€");
});
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ How? The function you pass to addEventListener runs when the event (e.g., click) happens.


πŸ€” Tricky Question: Can You Guess the Output?

const createCounter = () => {
  let count = 0;
  return () => ++count;
};

const counter1 = createCounter();
const counter2 = createCounter();

console.log(counter1()); // ?
console.log(counter1()); // ?
console.log(counter2()); // ?
console.log(counter2()); // ?
Enter fullscreen mode Exit fullscreen mode

Drop your guesses in the comments! πŸ”₯


Higher-order functions make your code cleaner, more powerful, and easier to maintain. Master them, and you'll feel like a JavaScript wizard πŸ§™β€β™‚οΈ in no time!

Top comments (2)

Collapse
 
hraifi profile image
sewiko

Nice explanation about Higher Order functions !!

Collapse
 
jagroop2001 profile image
Jagroop Singh

Thanks @hraifi