Call Stack in JavaScript

Call Stack in JavaScript

Interview Preparation

Hola Coders 🙋‍♀️!

In this article, we will learn a very important concept in JS which is Call Stack. It is a commonly asked question during interviews as the working and basic architecture of JavaScript resides on it.

Call Stack is also named as 👇

  • Execution Context stack
  • Program Stack
  • Runtime Stack
  • Control stack
  • Machine stack

There is always a complaint about the notorious behavior of JavaScript which we will uncover here. To have a basic understanding read about how JS works here

Always remember, when a JavaScript program is executed, Global Execution Context is created. As we know in JS everything happens inside Execution Context.

Global Execution Context

Global Execution Context (GEC) is created in two phases: Memory Creation Phase and Code Execution Phase

Let's understand it with the help of the following example👇

let a = 10
let b = 20

function sum (n1 , n2) {
    return n1 + n2
}

let res = sum (a,b)

Memory Creation Phase

When we execute a JS program, Memory Execution Context is created inside Global Execution Context. In the creation of this phase memory is assigned to the variables and functions. Just remember variables are undefined and functions are scanned as it is.

image.png

Code Execution Phase

In this phase, code is executed line by line ( synchronous single-threaded ) and values are assigned to each variable. Whenever we encounter any function then a new execution context is created which is pushed in the call stack and as soon as the function is executed completely the execution context is removed from the call stack.

image.png

Memory Execution for sum function

image.png

In this case variables are assigned the values, when the function is encountered an execution context has been created for the sum function. It will now execute in two phases: memory creation phase and code execution phase.

Code Execution for sum function

image.png

When the return keyword is encountered, It returns the control back to the global context to the line where it was called and also the function execution context is deleted.

Conclusion

  • JavaScript manages code execution context creation and deletion with the help of Call Stack.
  • Call Stack keeps the track of multiple function calls.

The End

I hope you enjoyed the article and had a good learning experience.

Follow for more articles and keep sharing👩

Keep coding

Linkedin

hashnode blogs

Did you find this article valuable?

Support akshita garg by becoming a sponsor. Any amount is appreciated!