🚀 Higher Order Functions in JavaScript: Let's Dive In!
Jagroop Singh

Jagroop Singh @jagroop2001

About: 👨‍💻 Full Stack Developer | 🤖 Machine Learning Developer | 🤝 Dev Relations Pro – 💼 Available for Hire | 24k+ Followers | 355k+ Views

Location:
India
Joined:
Apr 5, 2022

🚀 Higher Order Functions in JavaScript: Let's Dive In!

Publish Date: Nov 19 '24
53 12

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!

Comments 12 total

  • sewiko
    sewikoNov 19, 2024

    Nice explanation about Higher Order functions !!

  • john
    johnNov 19, 2024

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

    Is it correct ?

    • Jagroop Singh
      Jagroop SinghNov 20, 2024

      It's absolutely correct!!
      Well you understand HOF

  • Web
    WebNov 19, 2024

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

  • jawad abbas
    jawad abbasNov 19, 2024

    Nice explanation

  • BobbyleeX
    BobbyleeXNov 22, 2024

    1
    2
    2
    4
    Hope am correct 😁🤣

    • Jagroop Singh
      Jagroop SinghNov 22, 2024

      @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
  • ANIRUDDHA  ADAK
    ANIRUDDHA ADAKNov 22, 2024

    wow amazing .

  • Muhammad Usama
    Muhammad UsamaNov 26, 2024

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

Add comment