Anyone familiar with programming, already knows what functions do and how to use them.
But, what exactly is a callback function?
Let’s start with what a function is.
A function is a block of code that can be executed repeatedly, as needed. Functions are really useful because you write the code once and then you can run it multiple times.
To run the code inside a function, simply call the function.
Here’s an example that defines a function and then calls it ‒
In the code sample above, we created a function called greet() (lines 1 ‒ 3) that has a parameter called name. This parameter serves as a placeholder so that when the function is called, a value can be passed to the parameter.
In line 6, we called the greet() function and we passed the string value ‘John’ as an argument.
A callback function is simply a function that is passed into another function as an argument, which is then triggered when the other function is executed.
The following is an example of using a simple callback function.
Let’s start by creating an array of numbers that we will use in our example ‒
Here’s a function that checks for even numbers ‒
Now, we can pass the evenNumbers() function, described above, to the filter() method and assign it to the filteredEvenNumbers variable, as shown below ‒
In this example, the evenNumbers() function is a callback function, because it is being passed as an argument to another function.
Synchronous Callback Functions
The evenNumbers() function we created is an example of a synchronous callback function.
Asynchronous Callback Functions
If you are familiar with setTimeout, then you’ve been using callback functions all along!
In the following example, we are going to use the setTimeout() method that only executes after 2 seconds ‒
The Next Step
I hope this tutorial has helped you understand what callback functions are and how to use them as easily as functions!
There is still much to learn about callback functions, so I encourage you to continue practicing and learning.
To practice using callbacks, check out Codesphere, an online code editor in which you can build, test, and deploy your apps all within a single tab of your browser.
Thanks for reading!