JavaScript Higher-Order Functions
A higher-order function in JavaScript is a function that either takes one or more functions as arguments or returns a function as its result.
They are a key feature of JavaScript’s functional programming capabilities and enable cleaner, more reusable code.
Quick Links
Understanding Higher-Order Functions
A higher-order function is a function that does one of two things:
- It takes another function as an argument (input).
- It returns a function as its output.
In JavaScript, functions are treated just like any other value — you can store them in variables, pass them around, and return them from other functions.
This ability makes your code more flexible and powerful. You can write functions that behave differently depending on the function you give them.
JavaScript has many built-in higher-order functions already, like map, filter, and forEach. These all take other functions as arguments to decide how to process the items in an array.
Example 1: Function as an Argument
In this example, we pass a function as an argument to another function. This allows us to reuse logic and customize behavior.
function greet(name) {
return "Hello, " + name;
}
function processUserInput(callback) {
const name = "Max";
console.log(callback(name));
}
processUserInput(greet);
function greet(name) {
return "Hello, " + name;
}
function processUserInput(callback) {
const name = "Max";
console.log(callback(name));
}
processUserInput(greet);
How It Works:
- greet(name): A function that returns a greeting message.
- processUserInput(callback): This function takes another function as a parameter.
- Inside processUserInput, the callback function is called with the name "Max".
- Since greet is passed in as the callback, it prints "Hello, Max" to the console.
Output
Hello, Max
Hello, Max
Example 2: Returning a Function
In this example, a function returns another function. This is useful when you want to create functions with specific behavior based on some input.
function multiplier(factor) {
return function(number) {
return number * factor;
};
}
const double = multiplier(2);
console.log(double(5));
function multiplier(factor) {
return function(number) {
return number * factor;
};
}
const double = multiplier(2);
console.log(double(5));
How It Works:
- multiplier(factor): This function returns another function that multiplies a number by the given factor.
- const double = multiplier(2): We create a new function called double that multiplies any number by 2.
- double(5): Calls the returned function with 5, and it returns 10.
Output
10
10
Example 3: Using map Function
The map function is a built-in higher-order function in JavaScript. It allows you to apply a function to each item in an array and return a new array with the results.
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(function(num) {
return num * 2;
});
console.log(doubled);
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(function(num) {
return num * 2;
});
console.log(doubled);
How It Works:
- numbers: This is our original array of numbers.
- map(): This method takes a function and applies it to every element in the array.
- Inside the function, each num is multiplied by 2.
- The result is stored in a new array called doubled.
Output
[2, 4, 6, 8, 10]
[2, 4, 6, 8, 10]
Example 4: Using filter Function
The filter function is a built-in higher-order function in JavaScript. It creates a new array that includes only the elements that pass a certain condition.
const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter(function(num) {
return num % 2 === 0;
});
console.log(evenNumbers);
const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter(function(num) {
return num % 2 === 0;
});
console.log(evenNumbers);
How It Works:
- numbers: This is the original array of numbers.
- filter(): This method takes a function that returns true for the elements you want to keep.
- The function checks if a number is even using num % 2 === 0.
- Only the even numbers are added to the new array evenNumbers.
Output
[2, 4, 6]
[2, 4, 6]
Example 5: Using forEach Function
The forEach function is used to execute a function once for each element in an array. It's commonly used to perform side effects like logging or updating values.
const planets = ["earth", "mars", "jupiter"];
planets.forEach(function(planet) {
console.log("I like " + planet);
});
const planets = ["earth", "mars", "jupiter"];
planets.forEach(function(planet) {
console.log("I like " + planet);
});
How It Works:
- fruits: An array containing names of fruits.
- forEach(): Loops through each item in the array.
- The function runs once for each fruit, printing a message like "I like earth".
Output
I like earth
I like mars
I like jupiter
I like earth
I like mars
I like jupiter
Example 6: Using find Function
The find function searches an array and returns the first element that satisfies a given condition. If no element matches, it returns undefined.
const numbers = [5, 12, 8, 130, 44];
const found = numbers.find(function(number) {
return number > 10;
});
console.log(found); // Output: 12
const numbers = [5, 12, 8, 130, 44];
const found = numbers.find(function(number) {
return number > 10;
});
console.log(found); // Output: 12
How It Works:
- numbers: An array of numbers.
- find(): Looks for the first number greater than 10.
- The function returns 12 because it is the first element that matches the condition.
- If no number was greater than 10, it would return undefined.
Output
12
12
Example 7: Using setTimeout Function
The setTimeout function executes a function after a specified delay. It takes a callback function as its first argument.
function sayHello() {
console.log("Hello after 2 seconds!");
}
setTimeout(sayHello, 2000);
function sayHello() {
console.log("Hello after 2 seconds!");
}
setTimeout(sayHello, 2000);
How It Works:
- sayHello(): A function that prints a message to the console.
- setTimeout(sayHello, 2000): Calls sayHello after 2000 milliseconds (2 seconds).
- sayHello is passed as a callback function to setTimeout.
- The message "Hello after 2 seconds!" appears in the console after a delay.
Output (after 2 seconds delay)
Hello after 2 seconds!
Hello after 2 seconds!
Example 8: Using reduce Function
The reduce function is used to reduce an array to a single value by applying a function to each element and accumulating the result.
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce(function(accumulator, currentValue) {
return accumulator + currentValue;
}, 0);
console.log(sum); // Output: 15
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce(function(accumulator, currentValue) {
return accumulator + currentValue;
}, 0);
console.log(sum); // Output: 15
How It Works:
- numbers: An array of numbers.
- reduce(): Applies the function to accumulate a sum of all numbers.
- accumulator: Keeps track of the running total.
- currentValue: The current number being processed.
- The initial value of the accumulator is set to 0.
- The final result is the sum of all numbers in the array, which is 15.
Output
15
15
Frequently Asked Questions
What is a higher-order function in JavaScript?
What is a higher-order function in JavaScript?
A higher-order function is a function that takes another function as an argument or returns a function as its result. This allows more flexible and reusable code.
What are some examples of higher-order functions in JavaScript?
What are some examples of higher-order functions in JavaScript?
Common higher-order functions include map, filter, reduce, forEach, and setTimeout. These accept other functions to process logic.
How is a higher-order function different from a regular function?
How is a higher-order function different from a regular function?
A regular function performs a task and returns a result. A higher-order function either takes or returns another function, giving it additional flexibility in behavior.
Why should I use higher-order functions?
Why should I use higher-order functions?
Higher-order functions make your code cleaner, more modular, and reusable. They help you abstract away logic and reduce code duplication.
Can I create my own higher-order functions in JavaScript?
Can I create my own higher-order functions in JavaScript?
Yes! You can define functions that accept or return other functions. This is common in custom utilities, libraries, and functional programming patterns in JavaScript.
What's Next?
Next, you'll learn about memoization in JavaScript. Memoization is a way to make your code run faster by remembering the results of expensive function calls. If the same input shows up again, the function can return the saved result instead of doing the work all over again. It’s a smart trick that helps improve performance, especially when working with slow or repeated operations.