Understanding the Components of JavaScript Order of Execution
What is JavaScript?
Being a beginner of JavaScript, you start to learn a lot of fundamentals of the coding language and data types that can be used in your code. Have you ever just looked at the code that you’re doing and start to think, how is JavaScript able to read and get our results to the console? JavaScript is a single-threaded programming language, with a single-threaded runtime, which means it has a single call stack. The call stack can run one set of code at a time.
What is the call stack?
A call stack is like a list of function invocations that keep track of what is being called or waiting to be returned. A good example to look at is to think of it as a pile of boxes and you want to add a box to a stack you would add it to the top, not the bottom. If you would want to remove a box from the pile, you can take it off from the top. The last box added in the pile will be taken out of the pile last. At JavaScript run time, as the interpreter is going through the source file, it creates a stack frame for each function that it encounters, then places that stack frame on a first and last out data structure.
In JavaScript, there is only one main stack where all the lines are getting pushed and popped out. Think of the call stack as the single thread of execution. Now, what happens if the call stack becomes empty?
The callback queue and Event Loop.
When the call stack is empty, it takes the first thing on the callback queue and pushes it on to the call stack. This callback queue will have some type of message or task inside of it and once this Event Loop sees that, it will take those messages and put them into the call stack one at a time, and executes them. The Event Loop is pretty much checking and taking care of all the queues and keeps on pushing the message in the call stack. This Event Loop continues until the closest or furthest in function returns, where the stack frame is popped off the stack.
What if a function that is in the call stack is asynchronous?
If a function was to be asynchronous, for example, setTimeout is an asynchronous function, then it should be added to the Web API. The Web API will take care of JavaScript operations when it takes longer to execute from the call stack. Once it is executed in the Web API, it will then be added to the callback queue. While the async function is being executed, if there are other functions in the stack, they will continue to run so that the code is not blocked. That is why the Web API is taking care of the asynchronous function, so you won’t run into a block with your code.
To make it even more simple, in this order of execution, that Event Loop is just going by task and task, mission by mission, from the queue to the stack behind the scenes so that the interpreter can read the code line by line.