5.1 Key Concepts
Higher-order functions are a big part of functional programming and are widely used in JavaScript. They let us write more abstract, compact, and reusable code.
What are higher-order functions?
Higher-order functions are functions that take other functions as arguments or return functions as results. They let you use functions as first-class objects, which helps create more abstract and modular programs.
Examples of higher-order functions
- Passing functions as arguments.
- Returning functions from other functions.
5.2 Passing Functions as Arguments
Using built-in array methods
JavaScript provides tons of built-in methods for working with arrays that are higher-order functions, like forEach()
, map()
, filter()
, reduce()
, and others.
1. Method forEach()
The forEach()
method executes a given function once for each element in the array.
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(number) {
console.log(number);
});
// Output: 1 2 3 4 5
2. Method map()
The map()
method creates a new array with the results of calling a specified function for each element in the array.
const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map(function(number) {
return number * number;
});
console.log(squaredNumbers);
// Output: [1, 4, 9, 16, 25]
3. Method filter()
The filter()
method creates a new array with all elements that pass the test implemented by the provided function.
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(function(number) {
return number % 2 === 0;
});
console.log(evenNumbers);
// Output: [2, 4]
4. Method reduce()
The reduce()
method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce(function(total, number) {
return total + number;
}, 0);
console.log(sum);
// Output: 15
5.3 Returning Functions from Other Functions
Higher-order functions can return other functions, which allows for creating more flexible and customizable functions.
1. Currying
Currying is the process of transforming a function that takes multiple arguments into a function that takes one argument and returns another function that takes the next argument, and so on.
Example of currying:
function multiply(a) {
return function(b) {
return a * b;
};
}
const multiplyByTwo = multiply(2);
console.log(multiplyByTwo(5)); // Output: 10
const multiplyByThree = multiply(3);
console.log(multiplyByThree(5)); // Output: 15
2. Creating Customizable Functions
Higher-order functions allow creating functions that can be customized with arguments.
Example:
function createGreeting(greeting) {
return function(name) {
console.log(`${greeting}, ${name}!`);
};
}
const sayHello = createGreeting('Hello');
sayHello('Alice'); // Output: Hello, Alice!
const sayHi = createGreeting('Hi');
sayHi('Bob'); // Output: Hi, Bob!
5.4 Practical Use
Let's look at practical uses of higher-order functions.
Function compose()
The compose()
function lets you combine several functions into one that applies them in sequence:
function compose(...functions) {
return function(initialValue) {
return functions.reduceRight((value, func) => func(value), initialValue);
};
}
const addOne = x => x + 1;
const double = x => x * 2;
const addOneAndDouble = compose(double, addOne);
console.log(addOneAndDouble(5)); // Output: 12 (first adds 1 to 5, then doubles the result)
Asynchronous Higher-Order Functions
Asynchronous higher-order functions let you handle async operations like API requests or working with timers:
function fetchData(callback) {
setTimeout(() => {
callback('Data received');
}, 1000);
}
function processData(data) {
console.log(data);
}
fetchData(processData);
// Output: Data received (after 1 second)
GO TO FULL VERSION