Higher-order functions are such functions that take other functions as arguments or return functions as output. In JavaScript, you can pass functions as arguments to other functions or return them as output from functions. This allows you to write reusable, modular code that can be customized and extended through the use of callback functions.
Here’s an example of a function that takes a callback function as an argument:
function greet(callback) {
console.log("Hello!");
callback();
}
function sayHi() {
console.log("Hi!");
}
greet(sayHi);
Output:
Hello!
Hi!
In this example, the greet() function takes a callback function as its argument and calls it after logging a greeting. The sayHi() function is passed as the callback function and is called when the callback() function is called inside the greet() function.
Here’s another example of a function that returns a function:
function createGreeting(greeting) {
return function(name) {
console.log(`${greeting}, ${name}!`);
};
}
const sayHello = createGreeting("Hello");
sayHello("John");
Output:
Hello, John!
In this example, the createGreeting() function takes a greeting as its argument and returns a function that takes a name as its argument and logs a personalized greeting. The returned function is assigned to the sayHello variable and is called with the argument “John”.
Here are some examples of higher-order functions in JavaScript:
forEach()
The forEach() function is a method on arrays that allows you to iterate over the elements of an array and perform a specific action on each element. It takes a callback function as its argument, which is a function that will be called for each element in the array.
Here’s an example of using forEach() to print the elements of an array:
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(number) {
console.log(number);
});
Output:
1
2
3
4
5
map()
The map() function is a method on arrays that allows you to transform the elements of an array into a new array. It takes a callback function as its argument, which is a function that will be called for each element in the array. The callback function should return the transformed value for each element.
Here’s an example of using map() to double the value of each element in an array:
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(function(number) {
return number * 2;
});
console.log(doubledNumbers);
Output:
[2, 4, 6, 8, 10]
filter()
The filter() function is a method on arrays that allows you to select elements from an array based on a certain criteria. It takes a callback function as its argument, which is a function that will be called for each element in the array. The callback function should return a boolean value indicating whether the element should be included in the new array.
Here’s an example of using filter() to select only even numbers from an array:
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(function(number) {
return number % 2 === 0;
});
console.log(evenNumbers);
Output:
[2, 4]
reduce()
The reduce() function is a method on arrays that allows you to perform a reductive operation on the elements of an array. It takes a callback function as its argument, which is a function that will be called for each element in the array. The callback function should return the reduced value.
Here’s an example of using reduce() to calculate the sum of an array of numbers:
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce(function(accumulator, currentValue) {
return accumulator + currentValue;
}, 0);
console.log(sum);
Output:
15
Practice Exercise
- Which of the following is NOT a higher-order function in JavaScript?
a.map()
b.filter()
c.reduce()
d.sort() - The _______ function is a method on arrays that allows you to transform the elements of an array into a new array.
a.map()
b.filter()
c.reduce()
d.sort() - The
forEach()function returns a new array with the modified elements.
a. True
b. FAlse - How does the reduce() function differ from the map() function?
- Write a function called
findMaxValuethat takes an array of numbers and returns the maximum value. Hint: use thereduce()higher-order function to accomplish this. - Which of the following is NOT a valid use case for higher-order functions?
a. Iterating over an array and performing an action on each element
b. Filtering an array based on certain criteria
c. Transforming the elements of an array into a new array
d. Sorting an array in ascending or descending order - The _______ function is a method on arrays that allows you to select elements from an array based on certain criteria.
a.map()
b.filter()
c.reduce()
d.sort() - Higher-order functions are only useful for simple tasks.
a. True
b. False - Which of the following is NOT a valid use case for the
map()function?
a. Converting a list of temperatures from Celsius to Fahrenheit
b. Translating a list of words into a different language
c. Extracting the first names from a list of full names
d. Sorting an array in ascending or descending order - The
reduce()function is only useful for simple tasks such as calculating a sum or average.
a. True
b. False - How could the
forEach()function be used to implement a basic search feature on a website? - Write a function called
formatPhoneNumbersthat takes an array of phone numbers and returns a new array with the phone numbers formatted as “(123) 456-7890”. Hint: use themap() higher-orderfunction to accomplish this.
I hope this tutorial has helped you understand higher-order functions in JavaScript! Let me know if you have any questions.
