Higher Order Functions
Lesson Objectives
Explain what is a higher order function
Explain what is the purpose of a higher order function
Write a higher order function with a callback
A function that takes another function as an argument is called a higher order
function. The function that is being passed in is called a callback
.
Why would we use higher order functions and callbacks?
We want control of when a function gets executed (a callback happens after the higher order function hase been called) - this is how we can have some control of the order of function execution in an asynchronous language like JavaScript
We want to stack functionality. For example, we may want something to happen after a certain amount of time and thus use a built in function that sets time for us. Have you learned about array iterators yet? How do they stack functionality?
Let's think about a higher-order function we've already used: setTimeout
. This funciton splits functionality apart into
waiting 5 seconds
then triggering some other function
Code Along
Let's create some employees to do some important task for their boss.
Let's create a function called boss
. boss
's role will be to call employees to do her bidding.
Let's get or boss to boss our employees around
Our boss can even summon an anonymous function
What is the higher order function in the boss/employee example? What is the callback?
Another Example
Let's say we are going to manipulate a lot of words - we are working on a new text editor with a lot of custom editing. We can write a function that will capitalize every word:
We also want to be able to put an exclamation point on the end of each word
This lesson was adaped from SEI-MAE
Last updated
Was this helpful?