Skip to main content

What is the call stack (call stack)?

The call stack is a data structure that the JavaScript engine uses to track the execution of functions in a program.

How it works

While executing code, JavaScript needs to know:

  • which function is running right now,
  • where it was called from,
  • where to return after it finishes.

For this it uses the call stack - a structure that works on the LIFO principle (Last In - First Out).

What this looks like in practice

Example:

javascript
function a() { console.log('a'); b(); } function b() { console.log('b'); c(); } function c() { console.log('c'); } a();

Step by step:

  1. a() is called -> pushed onto the stack. Stack: [a]
  2. a() calls b() -> b() is added. Stack: [a, b]
  3. b() calls c() -> c() is added. Stack: [a, b, c]
  4. c() finishes -> it is removed. Stack: [a, b]
  5. b() finishes -> it is removed. Stack: [a]
  6. a() finishes -> it is removed. Stack: [] (empty)

What happens with infinite recursion

If a function calls itself with no exit:

javascript
function recurse() { recurse(); } recurse();

Every call is added to the stack, but is never removed. In the end, a "Stack overflow" error occurs, meaning the call stack has overflowed.

Relation to the Event Loop

JavaScript is single-threaded, meaning that at any given moment only one function from the stack is executing. When the stack is empty, the engine can take the next task from the callback queue and start a new Event Loop cycle.

Summary

TermDescription
Call StackWhere the engine stores the execution context of functions
LIFOLast called - first finished
Stack OverflowError when the stack overflows
Relation to Event LoopWhen the stack is empty, callbacks and promises are processed

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.