Understanding execution contexts is fundamental to understanding scope, hoisting, closures, and the this keyword.
What is an Execution Context?
Every time JavaScript runs code, it creates an execution context — an environment that contains all the information needed to execute that code.
Types of Execution Contexts
- Global Execution Context: Created when the script first runs. One per program.
- Function Execution Context: Created each time a function is called.
- Eval Execution Context: Created by eval() (don't use eval).
Creation Phase vs Execution Phase
The Call Stack
Stack Overflow
Variable Environment
This Binding
Each execution context also determines the value of this:
- Global context: this = window (browser) or global (Node)
- Function call: this = window (sloppy) or undefined (strict)
- Method call: this = the object
- Constructor: this = new object
- Arrow function: this = enclosing context (lexical)