Hoisting and Execution Context
What is the execution context stack (call stack) in JavaScript?
The execution context stack, commonly known as the call stack, is a data structure that tracks the execution of functions in a Last-In-First-Out (LIFO) order. It works as follows: 1. When JavaScript starts executing code, it creates a global execution context and pushes it onto the stack. 2. When a function is called, a new execution context is created for that function and pushed onto the top of the stack. 3. When the current function completes, its execution context is popped off the stack, and control returns to the context below it. 4. This process continues until the stack is empty. For example, consider this code: ```javascript function first() { console.log('First function'); second(); console.log('Back to first'); } function second() { console.log('Second function'); } first(); ``` Here's how the call stack would change: 1. Push global execution context 2. Call `first()` → Push `first`'s execution context 3. Log 'First function' 4. Call `second()` → Push `second`'s execution context 5. Log 'Second function' 6. `second()` completes → Pop `second`'s execution context 7. Log 'Back to first' 8. `first()` completes → Pop `first`'s execution context 9. Global code completes → Pop global execution context The call stack has a limited size, which is why deeply nested function calls or infinite recursion can lead to a 'stack overflow' error.