The JS engine goes through every line of code in your application and has to make decisions about when that code should be run.
The Infamous Call Stack
A stack is a common data structure. It functions exactly the stack of pancakes my dad makes for the whole family during the holidays – one at a time, people are able to remove a pancake from the top of the stack and to their plate. A stack works the same way – data on top of the stack can be removed, as well as added to the top of the stack until it needs to be processed.
The call stack is a special kind of stack in the JS engine. It processes one line of code at a time, and it executes whatever is on top of the stack. As soon as that function is finished executing, it is removed from the stack, and the line that was previously second in line is pushed to the top and executed.
Callbacks and Event Queues
Say we arrive at a line of code that needs this asynchronous behavior. Maybe you wrote a setTimeOut in your code to invoke a function at a later time, or perhaps a function that needs to get data from the database. These are called callback functions and the JS engine has a special way of handling them.
Instead of putting them directly into the call stack, the JS engine puts them into an event queue where it waits to be executed. Once the call stack is empty, it checks out the event queue and moves any function that is next in line to the call stack where it is executed.