Higher-Order Functions
Understand functions that take or return other functions.
Higher-order functions are functions that operate on other functions, either by taking them as arguments or by returning them. This is a core concept in functional programming and enables powerful patterns like callbacks, decorators, and array methods like map, filter, and reduce. Mastering higher-order functions will significantly improve your JavaScript skills.
📚 Concepts & Theory
Functions as Arguments
function greet(name, formatter) {
return formatter(name);
}
function loudGreeting(name) {
return name.toUpperCase() + "!";
}
greet("Alice", loudGreeting); // "ALICE!"
Functions as Return Values
function multiplyBy(factor) {
return function(number) {
return number * factor;
};
}
const double = multiplyBy(2);
const triple = multiplyBy(3);
double(5); // 10
triple(5); // 15
Built-in Higher-Order Functions
const numbers = [1, 2, 3, 4, 5];
// map - transform each element
numbers.map(n => n * 2); // [2, 4, 6, 8, 10]
// filter - keep elements passing test
numbers.filter(n => n > 2); // [3, 4, 5]
// reduce - accumulate to single value
numbers.reduce((sum, n) => sum + n, 0); // 15
Composition
const add10 = x => x + 10;
const multiply2 = x => x * 2;
const compose = (f, g) => x => f(g(x));
const add10ThenDouble = compose(multiply2, add10);
add10ThenDouble(5); // 30 (5+10=15, 15*2=30)
🎯 Your Challenge
Create a function `createGreeter` that takes a greeting string and returns a new function. The returned function should take a name and return the full greeting. Example: createGreeter("Hello")("World") should return "Hello, World!".
📝 Starter Code
// Create a function factory for greetings
function createGreeter(greeting) {
// Return a function that takes a name
}
// Test it
const sayHello = createGreeter("Hello");
const message = sayHello("World");
// message should be "Hello, World!"
- Return a function, not a value
- The returned function can access the outer function parameters
- Use template literals for clean string formatting
- Test with chained calls: createGreeter("Hi")("Alice")
Solution
function createGreeter(greeting) {
return function(name) {
return `${greeting}, ${name}!`;
};
}
const sayHello = createGreeter("Hello");
const message = sayHello("World");
Explanation
createGreeter is a higher-order function that returns a new function. The returned function closes over the greeting variable, remembering it. When we call sayHello("World"), it combines the stored "Hello" with "World".
⚠️ Common Mistakes to Avoid
- Returning the result instead of a function
- Not understanding closures with returned functions
- Forgetting to invoke the returned function
- Confusing function definition and invocation