Topic 3 of 37
Global Execution Context
Overview
Whenever JavaScript code runs, it runs inside an Execution Context. The Global Execution Context is the default one created when your script starts. It consists of the Global Object (like 'window' in browsers) and the 'this' keyword. Understanding this is foundational for knowing how variables are stored and accessed.
Syntax
In the creation phase, memory is allocated for variables and functions (hoisting). In the execution phase, the code runs line by line.
Creation Phase vs Execution Phase
javascript
console.log(myVar); // undefined (due to hoisting)
var myVar = "Hello";
console.log(myVar); // "Hello"Common Pitfalls
- Polluting the global execution context by declaring too many global variables, which can lead to naming collisions.
Interview Tips
- Explain the two phases of the Execution Context: Memory Creation Phase and Code Execution Phase.
Real-World Example
The global context gives you access to web APIs.
example
javascript
// 'window' is part of the global execution context in a browser
window.setTimeout(() => {
console.log("Executed from global context API");
}, 1000);