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:
function a() {
console.log('a');
b();
}
function b() {
console.log('b');
c();
}
function c() {
console.log('c');
}
a();Step by step:
a()is called -> pushed onto the stack. Stack:[a]a()callsb()->b()is added. Stack:[a, b]b()callsc()->c()is added. Stack:[a, b, c]c()finishes -> it is removed. Stack:[a, b]b()finishes -> it is removed. Stack:[a]a()finishes -> it is removed. Stack:[](empty)
What happens with infinite recursion
If a function calls itself with no exit:
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
| Term | Description |
|---|---|
| Call Stack | Where the engine stores the execution context of functions |
| LIFO | Last called - first finished |
| Stack Overflow | Error when the stack overflows |
| Relation to Event Loop | When the stack is empty, callbacks and promises are processed |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.