33 Javascript Concepts — #9. Callback Queue and Event Loop

First of all, this story is based on Stephen Curtis -33 Fundamentals Every Javascript Developer Should Know and you can read it here.
I thought it is great concepts to know although it is not a requirement. So i decided to learn and explain these concepts one by one.

#9. Callback Queue and Event Loop

If you execute this code, the result will be like below.

If you didn’t predict the result, this post might be helpful to you.

JavaScript runtime in browser

We can think JavaScript runtime as a big container that includes all the things that we need in order to use JavaScript. JavaScript engine, WEB APIs and callback queue are the main elements that are included to JavaScript runtime.

Javascript Engine

A JavaScript engine is a computer program that execute JavaScript code and consist of callstack and memory heap.

WEB APIs

WEB APIs are everything related to the DOM, Timers like SetTimeout, Fetch API and even the console.log that we use all the time.
WEB APIs are functionalities provided to the engine but which are actually not part of the JavaScript language itself.

Callback queue

This is the data structure that contains all the callback functions that are ready to be executed

With this basic knowledge, let’t go back to our first code example.

As soon as the code is executed, console.log(‘world’) is placed in the callstack. However console.log(‘hello’) is placed in the WEB APIs since setTimout is a function that WEB APIs support. And then, because i set the timer to 0 second, it is immediately moved to callback queue

Note that the 0 millisecond (second argument of setTimeout function ) doesn’t mean it will be executed after 0 millisecond, but, it means that it will be moved to callbackqueue after 0 millisecond.

After step 1 ‘world’ is logged on the console and immediately removed from callstack. Since callback queue should wait until callstack is empty, it can’t be executed first. This is why world is logged before hello is logged on the console.

Finally when the call stack is empty, the callback function is passed to the stack so that it can be executed. And this happen by something called the event loop. So basically the event loop takes callback functions from the callback queue and puts them in the callstack so that they can be executed.

Conclusion

Today we learned about callback queue and event loop. I think understanding what is happening under the hood will be great fundamentals for your JavaScript skill.
Thank you for reading and hope this might be helpful to you!!!

reference : video

Junior React Front-end Developer, LinkedIn: https://www.linkedin.com/in/dh-kim-733227200/