In-Depth Introduction to Call Stack in JavaScript.

Learn how the function executed in JavaScript.

Image from Eaters Collective

What is StackĀ ?


Stack is a Data structure, which is similar to an array, except that we cannot access the elements using the index directly and we can only insert and delete elements at the Top of Stack(ToS).

We majorly perform 2 operations in stack

  • Push → Inserting an Element
  • Pop → Deleting an Element

Stack follows LIFO (Last In First Out)Ā , means

  • If stack encounter push operation then the element is inserted at the Top of the Stack(ToS),
  • If stack encounters pop operation the element at the Top of the Stack(ToS) is removed first.

In programming, the stack(call stack) is used to store the order of function call. So that we can store the latest function call at the top, once the function is executed, the last executed function can be removed from the stack.

JavaScript is Single threadĀ , meaning JavaScript can handle(executes) only one function at a time, So for this case, only one stack is enough to handle.

Single Thread → One Stack → One function execution at a time

EVENT LOOP

The event loop is one which, checks if there is any function call in the call stack, and takes the function call and executes it.

function one() {
var a = 10;
return a;
}

How the function will be executed internally

Let’s create a function,

function one() {
var a = 10;
return a;
}

When we call the function oneĀ ,

  • one is pushed to the call stackĀ ,
  • Then it executes line var a = 10; which is a variable creation so memory for a is created in heap (this is where memory for variables, objects, and functions are allocated )
  • Then the next line is executed return aĀ , this will return the value of aĀ .
  • Once the function is finished executing, then it is removed from the call stack.

call stack for functionĀ one

Now let’s look into another Example

function one(){
two();
}
function two() {
three();
}
function three() {
console.trace(ā€œCall Stackā€);
}
one();

call stack
  1. When the function call for one() is made, it is pushed to the call stack.
  2. Inside the one function another function call to two() is made. So now the two is pushed to the call stack, and the control is transferred to function two.
  3. Inside two another function call to three() is made. So three is pushed to the call stack, and the control is transferred to function three.
  4. The console.trace in function three will print the call stack, then there is no more statement to execute in function threeĀ , so, it will be removed from the call stack and the control go back to function two.
  5. In the function twoĀ , there is no more statement to execute, so two is removed from the call stack and the control transferred to the function oneĀ .
  6. In the function one there is no more statement to execute, now it also removed from the stack.

How many function call can be pushed toĀ Stack.

The Stack is a data structure there will some certain amount of memory allocated to the call stack, So there is only a certain number of calls that can be pushed to the call stack. If the call stack is full then it will throw Maximum call stack size exceeded(StackOverflow) exception.

Learn about exceptions here.

To get Maximum call stack size exceeded, we can

Maximum call stack sizeĀ exceeded
var i =0;
function test() {
console.log(i++);
test();
}

This will print the maximum number of calls we can push to the call stack of JavaScript.

Now let’s understand Async Function Execution.

Up to this, we learned that only one thing can be executed by JavaScript at a time, but not for async call.


Consider that we need to download a large image.

If JavaScript executes the downloadImage function and what if the internet is slow, then it blocks the page, everything will be frozen.

But JavaScript will handle this in another way using an asynchronous function.

An asynchronous function is a function which operates asynchronously via the event loop, using an implicit Promise to return its result.

In simple words, An asynchronous function is a function with two things, request and callback. callback function which will be executed once the response for the request is received.

Once the asynchronous function is called it is pushed to the call stack and the call back is pushed to WEB API’s(provided by Browser) this will handle the success of request, and then the remaining part of the asynchronous is executed, then the function call is removed from the call stack.

Once the WEB API receives the success for a request then it will push the corresponding callback to the callback queue (this is where callback are pushed, in that order the callback will be pushed to call stack). When event loop finds that the call stack is free, the callback from the message queue will be pushed to the call stack and the callback will be executed as a normal function execution.

Call stack for Asynchronous function

When it finds fetch call inside the downloadImage functionĀ , it sends the requestĀ , then executes the next line of the function.


Once the image is downloaded the callback is pushed to callback/message queue


If there is no current function is executing(if the call stack is empty), then it is pushed to call stack and executes the callback


The above case works similarly in setTimeOut also.

Visual representation of the event loop can be found here.

ReferencesĀ :

Flaviocopes, MDN, What the heck is the event loop anyway?Ā .

Thanks for Reading šŸ“–Ā . I hope you like this. If you found any typo or mistake send me a private note šŸ“ thanks šŸ™ 😊 .

Follow me JavaScript JeepšŸš™šŸ’ØĀ .

Leave a comment

Design a site like this with WordPress.com
Get started