An execution context in JavaScript is an environment where the code is evaluated and executed. It includes the code's current scope, variables, and references to other resources. Here's a breakdown with a example and details:
Example:
1. Types of Execution Contexts:
- Global Execution Context: This is the default context where the code that is not inside any function is executed. Variables and functions declared here are accessible anywhere in the code.
- Function Execution Context: Created when a function is invoked. Each function call has its own execution context.
- Eval Execution Context: Created when code is executed inside an `
eval()`function.
2. Phases of Execution:
- Creation Phase: During this phase, the JavaScript engine:
- Sets up the Global Object (like
windowin browsers). - Sets up the `
this`keyword. - Hoists variables and functions: Declarations are moved to the top of their scope.
- Sets up the Global Object (like
- Execution Phase: The code is executed line by line. Variables are assigned values, and functions are invoked.
3. Call Stack:
- The JavaScript engine uses a call stack to keep track of execution contexts. When a function is called, a new execution context is created and pushed onto the stack. When the function completes, the context is popped off the stack.
4. Lexical Environment:
- This is where variables and function references are stored. Each execution context has its own lexical environment. If a variable or function is not found in the current environment, the JavaScript engine looks in the outer environment.
4. Example Breakdown:
- Global Execution Context: When the script runs, the global context is created. The `
greet`function is hoisted and ready for use. - Function Execution Context: When `
greet("Alice")`is called, a new context is created. The variable `greeting`is hoisted and set to"Hello". Then the function logs"Hello, Alice!"to the console. - Call Stack: Initially, only the global execution context is on the stack. When `
greet`is called, its context is added to the stack. Once the function completes, its context is removed, leaving only the global context.