Introduction
In this article I will be going over what higher-order functions are, how to use them, and why they are important.
Variables, Values, and Functions
Before that, let's refresh the basics. You can assign values to a variable:
const x = 5;
const y = "hello";
const z = {object: true};
You can also pass in values into a function:
function foo(bar){
console.log(bar);
}
foo("hello world");
bar is a parameter, and you can refer to that value passed inside the function.
Okay, that's pretty simple, so what?
Functions As Values
In JavaScript, we can use functions as values! We can assign it to a variable, pass as a function, or return from a function.
function hello(){
console.log("hello world");
}
const x = hello; //notice that it's not hello()
x(); //you can call the variable since it holds function
A function can even be returned as a value:
function one(){
console.log(1)
}
function two(){
return one
}
const x = two;
const y = two();
Higher-Order Functions And Callback Functions
Functions are values just like a number or string. If you've heard that functions are first-class citizens in JavaScript, this is what it means.
function callbackFunction(){
console.log("hello world");
}
function higherOrderFunction(fn){
fn(); //we can call the function that we passed in!
}
higherOrderFunction(callbackFunction); //notice that it's not callbackFunction()
Just like values, we can refer to the argument passed into the function (higherOrderFunction). Since it's a function, we can call it like a regular function using parenthesis ().
The function being passed as an argument is often called a callback function, while the function accepting the callback function is called a higher-order function . It can be also considered a higher-order function if it only returns a function.
So to review:
- Functions can be assigned to variables
- Functions can be passed as an argument to other functions
- Functions can return other functions
- A function that is passed to a function is called a callback function
- A function that accepts a callback function is a higher-order function
- A function that returns a function is also a higher-order function
Example
Let's say I wanted create a function to sort my book. I want to sort it in alphabetical order by title. The structure would look something like this:
function sortBooks(books){
... // sort books in alphabetical order by title
}
const books = [book1, book2, book3];
sortBooks(books);
Perfectly normal. But now, I want the option to sort it by author. I'm going to have to make some changes:
function sortByTitle(books) {...};
function sortByAuthor(books) {...};
function sortBooks(books, sortBy){
if(sortBy === "title") {
return sortBooks(books) // sort books in alphabetical order by title
} else if (sortBy === "author") {
return sortByAuthor(books) // sort books in alphabetical order by author
}
}
const books = [book1, book2, book3];
sortBooks(books, "title");
sortBooks(books, "author");
If I wanted many different ways to sort, this might get messy. A good way to solve this problem is by passing in a function
function sortByTitle(books) {...}
function sortByAuthor(books) {...}
function sortBooks(books, sortingFunction){
return sortingFunction(books);
}
const books = [book1, book2, book3];
sortBooks(books, sortByTitle);
sortBooks(books, sortByAuthor);
Now, the function is more composable. I can use whatever sorting function I want and I don't have to impose those functions upon anyone using the package or library.
You might be wondering why we need a separate sortBooks function for that. Can't we do this?
function sortByTitle(books) {...};
function sortByAuthor(books) {...};
const books = [book1, book2, book3];
sortByTitle(books);
sortByAuthor(books);
Indeed you can, but when dealing with more complex systems, it's less reusable. We might have a structure that handles many methods and data.
class LibrarySystem(){
this._sortStrategy;
function setSortStrategy(sortingFunction) {
this._sortStrategy= sortingFunction;
}
function sortBooks(books) {
return this._sortStrategy(books); //reuse sort
}
function fetchBooks(bookSource){
const books = fetchBooks(bookSource);
return this._sortStrategy(books); //reuse sort
}
function combineBookLists(books1, books2){
const books = books1.concat(books2);
return this._sortStrategy(books); //reuse sort
}
//...etc
}
This is actually called the Strategy Pattern, and is very commonly used to make interchangeable parts of a code.
More Examples
Event Listeners
You might have heard about event listeners. In order to make a button work, you have to bind a function to it. In JavaScript, we bind functions to the DOM by adding event listeners.
function sayHello(){
console.log("hello");
}
const button = document.getElementById("btn"); // gets button
button.addEventListener("click", sayHello);
addEventListener is a higher-order function because it takes in a function. This is a very common way to bind a function to an event.
Array Methods
In JavaScript, there are array methods forEach,reduce, filter, and map. They are higher-order functions that allow you to modify arrays using your own callback functions.
function capitalizeNames(item){
return item.toUpperCase();
}
const books = ["Hyperion", "Do Androids Dream of Electric Sheep?", "A Song of Ice and Fire"];
books.map(capitalizeNames);
Timers
setTimeout and setInterval will run a function in relation to time. In order for them to work you need to pass in a function.
function sayHello(){
console.log("hello");
}
setTimeout(sayHello, 1000);
setInterval(sayHello, 500);
Go Do Stuff
Higher-order functions let you create composable and reusable code, and many interfaces often use them. You can use them as values just like any other values.
If you know how to pass in a number or string, then you know how to pass in a function. If you know how to return an object or boolean, then you know how to return a function. It's easier than you think, so go ahead and start trying it yourself!
function doStuff(you){
you()
}
doStuff(you)
go do stuff
Top comments (0)