Execution Contexts and the Call Stack
When JavaScript executes code, it does so inside execution contexts. The global execution context is created when a script starts. Function calls create function execution contexts, and modern JavaScript also has lexical environments associated with blocks and modules.
The call stack tracks active execution. Calling a function pushes a frame onto the stack. Returning from the function removes that frame. JavaScript code running on a single agent executes one piece of synchronous JavaScript at a time, which is why an expensive synchronous loop can block other work.
Basic Call Stack Flow
Reading the Call Stack
function third() {
console.log('third');
}
function second() {
third();
console.log('second');
}
function first() {
second();
console.log('first');
}
first();💡 Calling first pushes first onto the stack. Calling second pushes another frame, and calling third pushes another. The frames unwind in reverse order as each function returns.
Key Takeaways
- Function calls create execution frames.
- The call stack follows last-in-first-out behavior.
- Long synchronous work blocks the current JavaScript execution agent.
Knowledge Check
What happens when a function calls another function synchronously?