Higher-Order Functions & Callbacks
Learn how JavaScript treats functions as values that can be passed around, empowering incredibly flexible code.
Functions as First-Class Citizens
In JavaScript, functions are 'first-class citizens'. This means they are treated exactly like any other value (like a string or a number).
You can assign them to variables, store them in arrays, and most importantly: you can pass them as arguments to other functions.
What is a Higher-Order Function?
A Higher-Order Function (HOF) is simply a function that does at least one of two things: it takes another function as an argument, or it returns a new function.
The function that gets passed *in* is called a 'Callback' function. The HOF 'calls back' to your function whenever it needs to.
Why is this useful?
HOFs allow you to abstract away repetitive logic. Instead of writing a for loop every time you want to modify an array, you can use a HOF like .map().
The .map() function handles the looping logic, and you just pass it a tiny callback function that tells it what to do with each individual item.
The Callback Machine
Create a custom Higher-Order Function that loops over an array and applies whatever callback function you pass into it.
The Callback Machine
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Functions are first-class citizens: they can be treated just like variables.
- A Higher-Order Function takes a function as an argument or returns one.
- A Callback is the function being passed in as an argument.
- When passing a callback, do not include parentheses
()unless you want to execute it immediately.
Done with this concept?
Mark it complete to track your progress. No login needed.