DEV Community

Cover image for JS Event Loop and Call Stack
SURAJITSHAW
SURAJITSHAW

Posted on

JS Event Loop and Call Stack

Hello everyone ๐Ÿ‘‹, I hope you are doing great.

So, today you are going to learn An Overview of what JavaScript event loop and call stack are, and how JavaScript work visually.

Many JavaScript developers don't know how JavaScript works. If you are new to JavaScript, then this article will help to learn how JavaScript works.

โš™๏ธ JavaScript Engine
The JavaScript engine is a program that executes your JavaScript code. A popular example of a JavaScript engine is Google's V8 engine.

โš™๏ธ V8 Engine
The V8 engine is an open-source, high-performance JavaScript and Web Assembly engine written in C++. The V8 engine is used inside Google Chrome, Node.js, and electron, among others.

Event Loop : The event loop is the secret behind JavaScriptโ€™s asynchronous programming. JS executes all operations on a single thread, but using a few smart data structures, it gives us the illusion of multi-threading. Letโ€™s take a look at what happens on the back-end.

Call Stack : The call stack is responsible for keeping track of all the operations in line to be executed. Whenever a function is finished, it is popped from the stack.

Image of call stack and it's function push and pop

Event Queue : The event queue is responsible for sending new functions to the track for processing. It follows the queue data structure to maintain the correct sequence in which all operations should be sent for execution.

Image of a queue

Whenever an async function is called, it is sent to a browser API. These are APIs built into the browser. Based on the command received from the call stack, the API starts its own single-threaded operation.

An example of this is the setTimeout method. When a setTimeout operation is processed in the stack, it is sent to the corresponding API which waits till the specified time to send this operation back in for processing.

Where does it send the operation? The event queue. Hence, we have a cyclic system for running async operations in JavaScript. The language itself is single-threaded, but the browser APIs act as separate threads.

The event loop facilitates this process; it constantly checks whether or not the call stack is empty. If it is empty, new functions are added from the event queue. If it is not, then the current function call is processed.

whole diagram of JavaScript environment

Thanks for reading! My name is Surajit Shaw; I love to share my learning with others. You can follow me on Twitter if youโ€™d like to learn about web development and JavaScript.

Here's a link where I explain how JavaScript work much briefly Understanding of JavaScript Function Executions.

Discussion (0)