A higher-order function takes another function as an argument or returns a function. They are the building blocks of clean, reusable JavaScript.
Save
Complete lesson & earn 250 PX
EXERCISE
1A higher-order function is any function that takes another function as an argument or returns a function. You have already used them without knowing it.
Save
The name sounds fancy, but you have already seen this in action. Any function that accepts or returns another function is a higher-order function (HOF).
setTimeout is a higher-order function:
setTimeout(function() {
console.log("This runs after 2 seconds");
}, 2000);
// setTimeout takes a function as its first argument
// That makes setTimeout a higher-order function
// The function you passed is a callback
Array methods are higher-order functions:
var numbers = [1, 2, 3, 4, 5];
// .map() takes a function -> HOF
var doubled = numbers.map(function(n) { return n * 2; });
console.log(doubled); // [2, 4, 6, 8, 10]
// .filter() takes a function -> HOF
var big = numbers.filter(function(n) { return n > 3; });
console.log(big); // [4, 5]
// .forEach() takes a function -> HOF
numbers.forEach(function(n) { console.log(n); });
// 1 2 3 4 5
Building your own higher-order function:
function applyToAll(array, transform) {
var result = [];
for (var i = 0; i < array.length; i++) {
result.push(transform(array[i]));
}
return result;
}
var prices = [10, 20, 30];
var withTax = applyToAll(prices, function(price) {
return price * 1.1;
});
console.log(withTax); // [11, 22, 33]
> Key Insight: Higher-order functions are the building blocks of clean . Instead of writing a new loop every time you want to transform data, you write the logic once and pass different functions for different transformations. This is the heart of in JavaScript.
HOFs accept or return functions. setTimeout, map, filter are all HOFs. They let you extract changing logic into callbacks while reusing the loop structure (DRY principle).