What is the call stack?
The call stack tracks which functions are currently running. It works last-in, first-out (LIFO).
Push — calling a function adds a frame to the top.
Pop — when a function returns, its frame is removed.
Single thread — JavaScript has one call stack, so it does one thing at a time.
Watch out: too much recursion overflows the stack ("Maximum call stack size exceeded"); async work is offloaded via the event loop.
function first() {
console.log('first start');
second();
console.log('first end');
}
function second() {
console.log('second start');
third();
console.log('second end');
}
function third() {
console.log('third');
}
first();
// Stack: [first] -> [first, second] -> [first, second, third]
// -> [first, second] -> [first] -> []
// Output: first start, second start, third, second end, first end
// Stack overflow
function infinite() {
infinite(); // No base case!
}
// infinite(); // RangeError: Maximum call stack size exceededfirst pushes onto stack, calls second (pushes), which calls third (pushes). third finishes and pops. second finishes and pops. first finishes and pops. Stack grows with each nested call and shrinks as functions return. infinite() keeps pushing without popping — exceeds the stack size limit.
Know LIFO: last called = first to return. Single call stack = single-threaded.
Stack overflow from infinite recursion. The event loop moves async callbacks to the stack when it is empty — connecting call stack to event loop shows complete understanding.