Understanding Higher-Order Funtions
Tags: javascript, webdev, tutorial, programming
Published: 2023-12-04 02:15:33

## Introduction
In this article I will be going over what higher-order functions are, how to use them, and why they are important.
&nbsp;
## Variables, Values, and Functions
Before that, let's refresh the basics. You can assign values to a variable:
```js
const x = 5;
const y = "hello";
const z = {object: true};
```
You can also pass in values into a function:
```js
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?
&nbsp;
## 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.
```js
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:
```js
function one(){
	console.log(1)
}
function two(){
	return one
}
const x = two;
const y = two();
```
&nbsp;
## 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.
```js
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

&nbsp;

- 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

&nbsp;
## 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:
```js
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:
```js
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
```js
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?
```js
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.
```js
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.
&nbsp;
## 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.
```js
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.
```js
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.
```js
function sayHello(){
	console.log("hello");
}
setTimeout(sayHello, 1000);
setInterval(sayHello, 500);
```
&nbsp;
## 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!
```js
function doStuff(you){
	you()
}
doStuff(you)
```
*go do stuff*