Callbacks
Define a callback function
Demonstrate ability to pass a function as a parameter
Functions may seem very different than the other javascript items we've worked with before, but don't be fooled! Functions are still first-class values, which means you can
store them in variables
pass them as arguments to other functions
create them within functions
return them from functions
If this all seems very strange, you could think of a javascript function as a javascript object that stores code to be run instead of key/value pairs. A callback function is just a regular function that we pass as an argument to another function!
Take a look at this example:
When we pass a function into another function as a paramenter, we are passing the function definition, so it can be called at a later time (hence the name callback). Notice the different outputs in the below example. First we print the function itself, then we call the function and print the output.
Anonymous Functions
If you define a function that is only going to be used as a callback, and not called anywhere else, you can pass skip the functioning declaration and just define it as an anonymous function within the encompassing function call itself. An anonymous function is a function that isn't stored in a variable.
Exercise: call testTypes
and pass in a anonymous function that takes one argument and prints that argument using console.log
.
Last updated
Was this helpful?