Bird
Raised Fist0
Javascriptprogramming~15 mins

Global execution context in Javascript - Deep Dive

Choose your learning style10 modes available
Overview - Global execution context
What is it?
The global execution context is the first environment created when a JavaScript program runs. It sets up the space where all your code starts executing. This context holds global variables, functions, and the special object called 'global' or 'window' in browsers. It stays active as long as your program runs.
Why it matters
Without the global execution context, JavaScript wouldn't know where to start running your code or how to organize variables and functions. It acts like the main stage where everything begins. If it didn't exist, your code would have no place to live or run, making programming impossible.
Where it fits
Before learning about the global execution context, you should understand basic JavaScript syntax and variables. After this, you can learn about function execution contexts, the call stack, and how JavaScript manages memory and scope.
Mental Model
Core Idea
The global execution context is the main workspace where JavaScript starts running your code and keeps track of all global variables and functions.
Think of it like...
Imagine the global execution context as the main office in a company where all employees (variables and functions) are registered and managed before they start working in their departments (functions).
┌───────────────────────────────┐
│       Global Execution Context │
│ ┌───────────────┐             │
│ │ Global Object │             │
│ └───────────────┘             │
│ ┌───────────────┐             │
│ │ Global Scope  │             │
│ │ (variables &  │             │
│ │  functions)   │             │
│ └───────────────┘             │
└───────────────────────────────┘
Build-Up - 7 Steps
1
FoundationWhat is an execution context
🤔
Concept: Execution context is the environment where JavaScript code runs and variables/functions are stored.
When JavaScript runs, it creates an environment called an execution context. This environment keeps track of variables, functions, and the order of execution. The very first one created is the global execution context.
Result
You understand that code runs inside a container that holds variables and functions.
Understanding execution context is key to grasping how JavaScript organizes and runs code step-by-step.
2
FoundationGlobal execution context basics
🤔
Concept: The global execution context is created first and holds global variables and functions.
When your JavaScript program starts, the global execution context is created. It sets up the global object (like 'window' in browsers) and prepares the global scope where all global variables and functions live.
Result
You know where global variables and functions are stored and that this context lasts for the whole program.
Knowing the global context lasts throughout the program helps you understand variable lifetime and scope.
3
IntermediateCreation and execution phases
🤔Before reading on: do you think JavaScript runs your code line-by-line immediately, or does it prepare something first? Commit to your answer.
Concept: The global execution context has two phases: creation and execution.
First, JavaScript creates the global execution context by setting up the global object, creating the 'this' keyword, and allocating memory for variables and functions (hoisting). Then, it runs your code line-by-line, assigning values and executing functions.
Result
You understand why variables can be used before they are declared (hoisting) and how the global context prepares for execution.
Recognizing the two phases explains many confusing behaviors like hoisting and 'this' binding.
4
IntermediateGlobal object and 'this' keyword
🤔Before reading on: does 'this' inside global code refer to the global object or something else? Commit to your answer.
Concept: 'this' in the global execution context points to the global object.
In the global execution context, the 'this' keyword refers to the global object (window in browsers, global in Node.js). This means you can access global variables and functions as properties of 'this'.
Result
You can predict what 'this' means in global code and how global variables relate to the global object.
Understanding 'this' in the global context helps avoid bugs when accessing or modifying global variables.
5
IntermediateGlobal execution context and the call stack
🤔Before reading on: do you think the global execution context stays on the call stack or is removed after starting? Commit to your answer.
Concept: The global execution context is the bottom of the call stack and stays there until the program ends.
JavaScript uses a call stack to manage execution contexts. The global execution context is pushed first and remains at the bottom. When functions run, their contexts are pushed on top and popped off when done, but the global context stays until the program finishes.
Result
You understand how JavaScript tracks running code and why the global context never disappears during execution.
Knowing the global context stays on the stack clarifies how nested function calls work and how scope chains form.
6
AdvancedHoisting in the global context
🤔Before reading on: do you think function declarations and variable declarations behave the same during hoisting? Commit to your answer.
Concept: Function declarations and variable declarations are hoisted differently in the global execution context.
During the creation phase, function declarations are fully hoisted with their definitions, so you can call them before they appear in code. Variables declared with 'var' are hoisted but initialized as undefined until assignment. Variables declared with 'let' and 'const' are not accessible before declaration (temporal dead zone).
Result
You can predict when and how variables and functions are available in global code.
Understanding hoisting differences prevents common bugs with undefined variables or calling functions too early.
7
ExpertGlobal context in strict mode and modules
🤔Before reading on: does 'this' in the global context always point to the global object, even in strict mode or modules? Commit to your answer.
Concept: Strict mode and ES modules change the behavior of the global execution context, especially 'this' and variable declarations.
In strict mode, 'this' in the global context is undefined instead of the global object, preventing accidental global variable creation. ES modules have their own module scope, so variables are not added to the global object. This changes how the global execution context behaves compared to classic scripts.
Result
You understand how modern JavaScript environments modify the global context for safer and modular code.
Knowing these differences helps write secure, modular code and avoid subtle bugs with 'this' and globals.
Under the Hood
When JavaScript starts, it creates the global execution context which includes the global object, the global scope, and the 'this' binding. It first runs a creation phase where it scans the code to allocate memory for variables and functions (hoisting). Then it executes code line-by-line, updating variable values and running functions. The global context stays active on the call stack throughout the program's life, serving as the base environment for all code execution.
Why designed this way?
JavaScript was designed to have a single global environment to simplify starting code execution and managing global variables. This design allows easy access to global data and functions but also requires careful handling to avoid conflicts. The two-phase approach (creation and execution) was chosen to support hoisting, making code more flexible and forgiving for beginners.
┌───────────────────────────────┐
│ Global Execution Context       │
│ ┌───────────────┐             │
│ │ Creation     │             │
│ │ Phase:       │             │
│ │ - Setup global│             │
│ │   object     │             │
│ │ - Hoist vars │             │
│ │   & funcs    │             │
│ └───────────────┘             │
│           │                   │
│           ▼                   │
│ ┌───────────────┐             │
│ │ Execution    │             │
│ │ Phase:       │             │
│ │ - Run code   │             │
│ │ - Assign vals│             │
│ │ - Call funcs │             │
│ └───────────────┘             │
└───────────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does 'this' in global code always point to the global object? Commit yes or no.
Common Belief:'this' in global code always points to the global object (window or global).
Tap to reveal reality
Reality:In strict mode or ES modules, 'this' in global code is undefined, not the global object.
Why it matters:Assuming 'this' is always global can cause bugs when code runs in strict mode or modules, leading to unexpected errors or undefined values.
Quick: Are variables declared with let and const hoisted like var? Commit yes or no.
Common Belief:All variables are hoisted and accessible before declaration.
Tap to reveal reality
Reality:Variables declared with let and const are hoisted but not initialized, causing a temporal dead zone where accessing them before declaration throws an error.
Why it matters:Misunderstanding this leads to runtime errors and confusion about variable availability.
Quick: Does the global execution context get removed from the call stack after starting? Commit yes or no.
Common Belief:The global execution context is removed from the call stack once code starts running.
Tap to reveal reality
Reality:The global execution context stays at the bottom of the call stack until the program ends.
Why it matters:Thinking it disappears can confuse learners about how nested function calls and scope chains work.
Quick: Are function declarations and variable declarations treated the same during hoisting? Commit yes or no.
Common Belief:Function declarations and variable declarations behave the same during hoisting.
Tap to reveal reality
Reality:Function declarations are hoisted with their full definitions, while variables declared with var are hoisted but initialized as undefined.
Why it matters:Confusing these causes bugs like calling undefined variables or overwriting functions unintentionally.
Expert Zone
1
In browsers, the global object is 'window', but in Node.js it's 'global', affecting how global variables behave across environments.
2
The global execution context's scope chain includes only the global scope, but nested function contexts build on top, creating layered scopes.
3
Strict mode disables some default behaviors in the global context, like creating implicit globals, improving code safety but changing legacy assumptions.
When NOT to use
Relying heavily on the global execution context for storing data is discouraged in large applications because it can cause naming conflicts and hard-to-track bugs. Instead, use modules, closures, or classes to encapsulate data and avoid polluting the global scope.
Production Patterns
In real-world code, developers minimize global variables and use module systems (like ES modules or CommonJS) to create isolated scopes. The global execution context mainly serves as the starting point, while most logic runs inside functions or modules to keep code organized and maintainable.
Connections
Call stack
The global execution context is the base frame on the call stack.
Understanding the global context as the bottom of the call stack clarifies how JavaScript manages nested function calls and execution order.
Scope chain
The global execution context provides the global scope at the root of the scope chain.
Knowing the global scope anchors the scope chain helps explain how variable lookup works across nested functions.
Operating system process environment
Both provide a global environment where programs or scripts start and manage resources.
Seeing the global execution context like an OS process environment helps understand how code execution contexts isolate and manage resources.
Common Pitfalls
#1Using 'this' in global code assuming it always points to the global object.
Wrong approach:'use strict'; console.log(this.someVar); // Error: Cannot read property 'someVar' of undefined
Correct approach:var someVar = 5; console.log(window.someVar); // 5 (in browsers, accessing global object explicitly)
Root cause:Misunderstanding that 'this' is undefined in strict mode global code, not the global object.
#2Accessing let or const variables before declaration causing runtime errors.
Wrong approach:console.log(myVar); // ReferenceError let myVar = 10;
Correct approach:let myVar = 10; console.log(myVar); // 10
Root cause:Not knowing about the temporal dead zone for let and const variables.
#3Declaring global variables without var, let, or const, creating implicit globals.
Wrong approach:function foo() { x = 10; // creates global variable unintentionally } foo(); console.log(x); // 10
Correct approach:function foo() { let x = 10; // local variable } foo(); console.log(typeof x); // undefined
Root cause:Not using strict mode and misunderstanding variable declaration scope.
Key Takeaways
The global execution context is the first environment JavaScript creates to run your code and holds all global variables and functions.
It has two phases: creation (setting up variables and functions) and execution (running code line-by-line).
'this' in the global context usually points to the global object, but in strict mode or modules, it can be undefined.
Hoisting means function declarations and var variables are moved to the top during creation, but let and const behave differently.
The global execution context stays on the call stack throughout the program, serving as the base for all other execution contexts.

Practice

(1/5)
1. What does the global execution context in JavaScript contain?
easy
A. Global variables, functions, and the global object
B. Only local variables inside functions
C. Only the code inside loops
D. Only event listeners

Solution

  1. Step 1: Understand what global execution context is

    The global execution context is the environment where all JavaScript code runs initially, outside any function.
  2. Step 2: Identify what it holds

    It holds global variables, functions declared globally, and the global object (like window in browsers).
  3. Final Answer:

    Global variables, functions, and the global object -> Option A
  4. Quick Check:

    Global execution context = global variables + functions + global object [OK]
Hint: Global context holds everything outside functions [OK]
Common Mistakes:
  • Thinking it only holds local variables
  • Confusing with function execution context
  • Assuming it holds event listeners only
2. Which of the following is the correct way to declare a global variable in JavaScript?
easy
A. let myVar = 10;
B. function myVar() {}
C. const myVar;
D. var myVar = 10;

Solution

  1. Step 1: Identify global variable declaration syntax

    Using var outside any function declares a global variable in JavaScript.
  2. Step 2: Check other options

    function myVar() {} declares a function, not a variable. let and const can declare global variables but behave differently in scope and hoisting; const myVar; is invalid because const needs initialization.
  3. Final Answer:

    var myVar = 10; -> Option D
  4. Quick Check:

    Global variable declaration = var outside functions [OK]
Hint: Use var outside functions for global variables [OK]
Common Mistakes:
  • Using const without initialization
  • Confusing function declaration with variable
  • Assuming let always creates global variables
3. What will be the output of the following code?
var x = 5;
function test() {
  var x = 10;
  console.log(x);
}
console.log(x);
test();
console.log(x);
medium
A. 10 10 10
B. 5 5 5
C. 5 10 5
D. 10 5 10

Solution

  1. Step 1: Understand variable scopes

    var x = 5; declares a global variable x with value 5. Inside test(), var x = 10; declares a local variable x that shadows the global one.
  2. Step 2: Trace console.log outputs

    First console.log(x); outside function prints global x = 5. Inside test(), console.log(x); prints local x = 10. After calling test(), the last console.log(x); prints global x again, which is still 5.
  3. Final Answer:

    5 10 5 -> Option C
  4. Quick Check:

    Global x = 5, local x = 10 inside function [OK]
Hint: Local vars shadow globals inside functions [OK]
Common Mistakes:
  • Assuming global x changes after function call
  • Confusing local and global scopes
  • Expecting all outputs to be same
4. Identify the error in the following code related to global execution context:
console.log(a);
var a = 10;
medium
A. undefined because of hoisting of 'var a'
B. SyntaxError due to missing semicolon
C. 10 because 'a' is initialized before console.log
D. ReferenceError because 'a' is not defined

Solution

  1. Step 1: Understand hoisting of var declarations

    In JavaScript, var declarations are hoisted to the top of their scope with an initial value of undefined.
  2. Step 2: Trace the console.log output

    At console.log(a);, variable a exists but is not yet assigned 10, so it prints undefined.
  3. Final Answer:

    undefined because of hoisting of 'var a' -> Option A
  4. Quick Check:

    var hoisting = undefined before assignment [OK]
Hint: var declarations hoist but initialize as undefined [OK]
Common Mistakes:
  • Expecting ReferenceError instead of undefined
  • Thinking variable is initialized before console.log
  • Confusing var with let/const hoisting
5. Consider this code snippet:
var count = 1;
function increment() {
  count++;
  var count = 10;
  console.log(count);
}
increment();
console.log(count);
What will be the output and why?
hard
A. 10 1
B. NaN 1
C. 1 1
D. ReferenceError 1

Solution

  1. Step 1: Analyze variable hoisting inside function

    Inside increment(), var count is hoisted to the top of the function scope but not initialized yet, so it starts as undefined.
  2. Step 2: Evaluate the increment operation

    The line count++; tries to increment the local count which is undefined, setting it to NaN. Then count = 10; assigns 10, and console.log(count); prints 10.
  3. Step 3: Check global count after function call

    The global count remains unchanged at 1, so console.log(count); outside prints 1.
  4. Final Answer:

    NaN 1 -> Option B
  5. Quick Check:

    Local var hoisted undefined -> NaN on increment -> 10 on assignment [OK]
Hint: Hoisted local var undefined causes NaN on ++ [OK]
Common Mistakes:
  • Thinking the output is NaN 1 because of undefined++
  • Assuming increment affects global count
  • Ignoring hoisting of local var
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard