Facebook Pixel

JavaScript Call Stack Basics for Beginners

The call stack is the engine's tracker for function calls. Here is how it works and why stack overflows happen.

JavaScript Call Stack Basics for Beginners

The call stack is a data structure that tracks which function is currently running and what to return to when it finishes.

How It Works

  • The stack is LIFO: Last In, First Out.
  • When a function is called, a frame is pushed onto the stack.
  • The frame contains the function's arguments, local variables, and the return address.
  • When the function returns, its frame is popped.

Example

function greet() { sayHi(); console.log("done"); } function sayHi() { console.log("hi"); } greet();
  1. GEC is at the bottom.
  2. greet() is called, frame pushed.
  3. sayHi() is called inside, frame pushed on top.
  4. sayHi logs "hi" and returns, frame popped.
  5. greet logs "done" and returns, frame popped.
  6. Only GEC remains.

Stack Overflow

If functions keep calling each other without returning (infinite recursion), frames pile up until the engine's stack limit is hit. The engine throws a RangeError: Maximum call stack size exceeded.

function recurse() { recurse(); } recurse(); // RangeError

Why It Matters

  • The stack is single, so a long-running function blocks everything else.
  • The event loop only runs queued callbacks when the stack is empty.
  • Debugging stack traces are literal snapshots of the call stack at error time.

The Takeaway

The call stack tracks active function calls as a LIFO stack. Each call pushes a frame, each return pops one. Infinite recursion causes stack overflow. The stack must be empty before the event loop can run queued callbacks.

A LIFO data structure that tracks which function is currently running. Each function call pushes a frame, each return pops one. Only one function runs at a time.

Infinite or very deep recursion. Each call adds a frame to the stack without popping one, until the engine's maximum stack size is exceeded and a RangeError is thrown.

No. JavaScript is single-threaded, so the call stack has one active frame at a time. Other functions must wait for the current one to return.

Only when the call stack is empty. The event loop checks the stack, and if it is empty, it moves callbacks from the microtask queue (then macrotask queue) onto the stack.

The function's arguments, its local variables, the return address (where to resume in the caller), and the value of this for that invocation.

Ready to master React completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.
Please Login.
Please Login.