What is an execution context and call stack?
Practice this questionDefinition:
An execution context is the information JavaScript uses while running a piece of code, including its variables, scope and this value. The call stack tracks which function is currently running and where execution should return. Each function call adds a context, and returning removes it.
Key points:
-
An execution context holds the information needed to run some code.
-
The stack tracks active function calls; the latest call finishes first.
-
Deep recursion can overflow the stack; a long loop can block the thread.
-
A function's local variables are separate from the local variables of another call.
-
The stack handles synchronous execution; waiting network requests do not remain on it as active JavaScript calls.
Example:
function second() { return 2; }
function first() { return second() + 1; }
console.log(first()); // 3firstcallssecond, sosecondcompletes before execution returns tofirst.
Interview point:
- Explain stack overflow and event-loop blocking separately: one is excessive nested calls, the other is work holding the thread too long.
=> Stack overflow happens when the call stack becomes full because too many function calls are added to it. This usually happens because of deep or infinite recursion, where a function keeps calling itself without reaching a stopping condition.
=> Event-loop blocking happens when the JavaScript thread is busy doing a long-running or CPU-heavy task. Since JavaScript normally runs application code on a single main thread, other callbacks, requests, timers, and user interactions have to wait until that task finishes.