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 (12)

Collapse
 
john12 profile image
john

After reading the whole blog, questions answer is :
1
2
1
2

Is it correct ?

Collapse
 
jagroop2001 profile image
Jagroop Singh

It's absolutely correct!!
Well you understand HOF

Collapse
 
hraifi profile image
sewiko

Nice explanation about Higher Order functions !!

Collapse
 
jagroop2001 profile image
Jagroop Singh

Thanks @hraifi

Collapse
 
aniruddhaadak profile image
ANIRUDDHA ADAK

wow amazing .

Collapse
 
jagroop2001 profile image
Jagroop Singh

thanks @aniruddhadak

Collapse
 
bobbyleex profile image
BobbyleeX

1
2
2
4
Hope am correct 😁🤣

Collapse
 
jagroop2001 profile image
Jagroop Singh

@bobbyleex ,
Not quite! but still half is correct😄 Each call to createCounter creates a new independent counter with its own count variable.

Here’s what happens:

  • counter1() increments its own count variable: 1, then 2.
  • counter2() starts fresh and increments its own count: 1, then 2.

Output:

1
2
1
2
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jawad_abbas-090 profile image
jawad abbas

Nice explanation

Collapse
 
jagroop2001 profile image
Jagroop Singh

Thanks @jawad_abbas-090 @jawe

Collapse
 
works profile image
Web

I thinks it's answer is :
0
1
0
1
or
0 0 0 0

Collapse
 
muhammad_usama_db59ea3065 profile image
Muhammad Usama

answer is
1
2
1
2
if i add another log like
console.log(counter2());
then answer will be:
1
2
1
2
3