Blogger.

Understanding the Call Stack in JavaScript for Async Operations

Cover Image for Understanding the Call Stack in JavaScript for Async Operations
dev
dev

To Understand the async nature of JavaScript, we first need to understand why do we needed async operations in JavaScript and how this fits into the inner working of call stack which is the part of v8 engine which executes our code.

How JavaScript Code Gets Executed

So first of all how does JavaScript code gets executed ? JavaScript uses the V8 engine, developed by Google Chrome, to parse, compile, and execute code. The V8 engine consists of two main components:

1. Heap: Stores variables and objects 2. Call Stack: Tracks program execution and manages function calls

As JavaScript is single threaded language which means that it can only execute one task at a time so "A Single thread" language. Call stack manages the function calls made by the program and keep executing them by following the principle of "Last In First Out". Because functions cannot be stacked on top of each other randomly that's why LIFO principle is adopted by call stack.

The Call Stack in Detail

The call stack in JS is a data structure in the V8 engine which handles code execution and keeps track of the program's current position so that i can tell where the error occurred if any problem arises during code execution. Here's how it works:

1. When JavaScript code runs, a global execution context is created on the call stack. 2. The call stack follows the LIFO principle, executing the most recently added code first. 3. Synchronous code is executed directly on the call stack. 4. Asynchronous functions are handled differently: - They are moved to the browser's Web API - Once completed, they're added to the callback queue - The event loop moves them back to the call stack when it's empty

Detailed Walkthrough of Call Stack Code execution

- Before any task is executed a global execution context is created on the call stack, as the code which is about to be executed will be run line by line over the global execution context first .

flowchart of call stack in js

- The call stack makes a stack of variables and objects on top of each other to start the execution, the code is stacked on top of each other by following the principle of Last in First out, So whatever code get's stacked on top at the last in call stack will be the first code block to get's executed. the call stack executes any task that comes inside it . - If any code from the stack is of async nature (i.e - will take time to get's execute i.e async await functions, promises etc. ) they will be offloaded from call stack and send to the browser's web api. As the JavaScript is a single threaded language and non- concurrent language so it can only execute one task at a time and it also has only one stack so we will use that stack to execute all the program that we have wrote. The priority functions will be the first ones to get executed on the call stack. - The Web Api of the browser is like a extra support to the v8 engine of js which offers extra things during compilation of code. So the Async functions will se send to the Web Api and wait until all the synchronous functions get's executed and the data is fetched by async function.

- And When the async functions or the functions that were waiting for the data to be fetched or some promise to be fulfilled, are completed then they are send to the task queue ,As we can't send these completed function to the call stack immediately as there may be some other tasks being carried out in the call stack . - So the completed tasks are then send to the task Queue and there it waits for the Event Loop, as the event loops will send the completed tasks from the task Queue to the call stack when the call stack becomes empty. The Event Loop will not send the completed tasks that were send from the Web API to the task Queue directly to task queue but wait for task queue to be cleared completely and then the first task in the task Queue will be send to the call stack and it will then be executed. - There is also an extra queue with task queue that is called Microtask queue - But when we are working with promises instead of async functions then we are working with microtask queue the microtask queue is queue dedicated to - then, catch, and call back functions , , however the event loop priorities the microtask queue, so the microtask queue has to be empty and only after that the event loop starts sending tasks from task queue , and it also checks after executing tasks from task queue that whether or not the microtask queue is empty or not and then execute the task queue function

The Role of the Heap

The heap is a memory management system in the browser that: - Stores objects, Variables or other data in memory - Acts as a garbage collector, cleaning up unused objects - Retains objects with active references

Note:- Heap which works as garbage collector cleans up the objects which are not in use by the user to free up memory and it only keeps the objects in the memory who has some kind of reference to them. (In JavaScript, a reference is when a variable, property, or another data structure points to an object in memory.) and garbage collection kicks in when the object doesn't have any references and cleans up the objects in memory.

Asynchronous Operations and the Event Loop

To manage asynchronous operations, JavaScript utilizes:

1. Web API: Handles time-consuming or asynchronous tasks 2. Task Queue: Stores completed asynchronous functions 3. Event Loop: Moves tasks from the queue to the call stack when it's empty

There's also a Microtask Queue, which has higher priority and is used for Promise callbacks and mutation observers.

Why Understanding the Call Stack Matters

1. It helps in debugging and understanding error stack traces 2. It's crucial for managing asynchronous operations effectively 3. It provides insights into JavaScript's single-threaded nature and how it achieves concurrency

Understanding how code get's executed in call stack is important to know as it helps us visualize what is happening behind the scenes when our async code is getting executed.


Blog

Cover Image for Why Pattern Recognition Beats Memorizing Syntax for Learning New Languages

Why Pattern Recognition Beats Memorizing Syntax for Learning New Languages

using pattern recognition instead of rote memorization to learn new programming concepts and problem solving

Cover Image for AR Glasses: Revolutionizing the Way We Browse the Internet

AR Glasses: Revolutionizing the Way We Browse the Internet

As this technology continues to evolve, we can expect a future where the boundaries between the physical and digital worlds disappear, and information is always within sight