What is a higher order function
A higher-order function is a function that takes another function as an argument or returns a function.
Example 1: Takes a function as an argument
function greet(name) { return `Hello, ${name}`; } function processUser(callback) { console.log(callback("John")); } processUser(greet);
Output:
Hello, John
Example 2: Returns a function
function multiply(x) { return function (y) { return x * y; }; } const double = multiply(2); console.log(double(5)); // 10
Common Higher-Order Functions in JavaScript
-
map() -
filter() -
reduce() -
forEach() -
find() -
setTimeout()
Example:
const numbers = [1, 2, 3]; const doubled = numbers.map(num => num * 2);
Here, map() is a higher-order function because it takes a callback function.
Comments
Post a Comment