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 (5)
Nice explanation about Higher Order functions !!
Thanks @hraifi
After reading the whole blog, questions answer is :
1
2
1
2
Is it correct ?
I thinks it's answer is :
0
1
0
1
or
0 0 0 0
Nice explanation