Skip to main content

Command Palette

Search for a command to run...

Call Stack in JavaScript

Published
2 min readView as Markdown
Call Stack in JavaScript

What is call stack?

Call stack is a process in JavaScript which is used to keep track of functions. When we call a function, JavaScript will add that function to the call stack. If this function invokes another function, JavaScript will add that function to the call stack as well, above the first function.

This process will repeat with any other function that will be called by the previous function. When one function is finished, JavaScript will pop out that function from the call stack. There are two important things. The first thing is that every new function in the stack will be added to the top of the call stack and second is that the call stack is executed from the top to the bottom. The first function added to the stack will be executed as the last. This is also called the LIFO principle (Last-In-First-Out).

Example :-

function FuncOne() {
  return 'This is the one.'
}

function FuncTwo() {
  FuncOne()

  return 'this is two.'
}

// Call stack is still empty here

FuncTwo()

Call stack:

Step 1: FuncTwo() is invoked. An empty stack frame is created. It is the main (anonymous) entry point of the program.

Step 2: FuncTwo() added to the call stack.

Step 3: FuncTwo() calls FuncOne().

Step 4: FuncOne() is added to the call stack.

Step 5: FuncOne(), is executed.

Step 6: FuncOne() removed from the stack.

Step 7: JavaScript goes back to FuncTwo().

Step 8: any code left inside FuncTwo() after FuncOne() call is executed.

Step 9: FuncTwo() is removed from the stack.

Step 10: call stack is empty.

The key point in call stack are :-

  • It is synchronous and single-threaded language. Meaning it can only do one thing at a time and in a specific order.

  • It works as a LIFO — Last In First Out.