Careeroza
Execution Context & Call Stack
Execution Context
Every time a function is called, JavaScript creates an execution context: its local variables, its this and a link to the outer scope. Contexts are kept on the call stack: a function call pushes one, a return pops it.
The Call Stack in Action
Example
function first() {
console.log("first starts");
second();
console.log("first ends");
}
function second() {
console.log("second runs (stack: global → first → second)");
}
first();
console.log("back in global code");Output
first starts second runs (stack: global → first → second) first ends back in global code
Stack Overflow
Example (error)
A function that calls itself forever fills the stack:
function forever() {
return forever();
}
forever();Output
Uncaught RangeError: Maximum call stack size exceeded
Recursion always needs a base case that stops it (see Recursion examples in Advanced Functions).