Sobes.tech
Junior

How does the stack work in JavaScript?

sobes.tech AI

Answer from AI

Call Stack is a data structure that tracks the execution of functions. When a function is called, it is placed on top of the stack. When the function finishes, it is removed from the stack. JavaScript is single-threaded, so it has one call stack.

Main operations:

  • Push: Adding a function to the top of the stack.
  • Pop: Removing a function from the top of the stack.

Example:

// Function A calls function B
function A() {
  B(); // B is placed on the stack
  console.log('A finished'); // After B finishes, A continues
}

// Function B calls function C
function B() {
  C(); // C is placed on the stack
  console.log('B finished'); // After C finishes, B continues
}

// Function C simply logs to the console
function C() {
  console.log('C finished'); // C finishes, removed from the stack
}

A(); // Call A. A is placed on the stack.
// Stack: [A] -> [A, B] -> [A, B, C] -> [A, B] -> [A] -> []

Tracking the stack:

Action Stack
A() is called [A]
B() is called [A, B]
C() is called [A, B, C]
C() finishes [A, B]
B() finishes [A]
A() finishes []

Stack overflow errors occur when the stack fills up with too many calls (for example, in infinite recursion) and cannot add new functions.

How does the stack work in JavaScript? — Node.js - sobes.tech