What is a callback function?
The time at which it gets executed is either said specifically by the programmer, or is determined by interferences such as internet speed, large data processing, resource fetching, etc.
That's great and all, but who cares? When and why should I use them?
Instead, functions and code which are not a callback function will continue to get executed. Once that is finished (the stack clears), then the callback functions will execute in the order they were first encountered.
And that my friends, is what is known by the name of Asynchronous Programming.
You should care since callback functions can potentially speed up your website or application, because code execution does not stop and wait to finish its current process before moving on.
You should use callback functions whenever you need to get a resource (like images, text, audio), or process some data, but where you also do not want your program to stop and wait for the entire process to complete. After all, you don't want to make the end user, a visitor to your website or app, to have to wait too long otherwise they will get bored and leave.
That cool and everything, but let me see some code!
Sounds good. Let me walk you through a couple of examples:
In this first example, the console.log() function is declared first and executes first. Just as we'd expect it to.
However, an interesting thing happens...our code within the setTimeout() function executes after our final console.log(), which prints out to the console: "This executes second!"
Remember, the code that is not a callback function is not asynchronous, which means that code will execute immediately and will not be put on the backburner; unlike our callback functions.
This is why our code within the setTimeout function executes last in this example.
So, the execution order is: the first console.log() >>> the last console.log() at the end of our script >>> and then our console.log() found within the setTimeout function.
Our second example proceeds like so:
The myBtn event listener get's put into the heap, where it waits to get called upon mouse click.
This happens first.
What happens next is our console.log() at the end of the script gets called and prints its message to the console.
Lastly, our user finally clicks the button and console.log() prints, "I execute after the console.log() outside the event listener!"
Ultimately, callback functions help us keep our code running efficiently by not having our code stop and wait for the current function execution to finish.
Check out this awesome chapter from You don't know JS for a more in-depth explanation.
This is crazy cool...but what if I promised you a better way?