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:
- Takes another function as an argument.
- 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]
💡 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
💡 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"]
💡 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
💡 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! 🚀");
});
💡 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()); // ?
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)
After reading the whole blog, questions answer is :
1
2
1
2
Is it correct ?
It's absolutely correct!!
Well you understand HOF
Nice explanation about Higher Order functions !!
Thanks @hraifi
wow amazing .
thanks @aniruddhadak
1
2
2
4
Hope am correct 😁🤣
@bobbyleex ,
Not quite! but still half is correct😄 Each call to
createCounter
creates a new independent counter with its owncount
variable.Here’s what happens:
counter1()
increments its owncount
variable:1
, then2
.counter2()
starts fresh and increments its owncount
:1
, then2
.Output:
Nice explanation
Thanks @jawad_abbas-090 @jawe
I thinks it's answer is :
0
1
0
1
or
0 0 0 0
answer is
1
2
1
2
if i add another log like
console.log(counter2());
then answer will be:
1
2
1
2
3