Scope, Scope Chain, Hoisting & Variable Environments
After completing this chapter, you should be able to:
Explain how JavaScript determines variable accessibility.
Understand lexical scope and the scope chain.
Differentiate global, function, and block scope.
Explain hoisting without the misleading idea that code physically moves.
Understand why
var,let, andconstbehave differently before declaration.Understand how function calls create separate execution contexts.
Trace variable values across multiple function calls.
1. What is Scope?
Scope determines where a variable or function can be accessed in JavaScript.
In simple words:
Scope answers one question:
"From which parts of my code can I access this variable?"
Imagine you create a variable inside a function. Can you access that variable from outside the function?
No. Its accessibility is restricted by its scope.
Real-World Analogy: A Multi-Floor Office Building
Imagine a corporate building with three floors:
Ground floor: Reception (Global Scope)
First floor: Department office (Outer Function Scope)
Second floor: Private cabin (Inner Function Scope)
An employee working in the private cabin can access information available on their floor and the floors below.
However, someone standing at reception cannot access information stored inside a private cabin.
JavaScript follows a similar rule: inner scopes can access variables from their outer lexical scopes, but outer scopes cannot access variables declared exclusively inside inner scopes.
2. Types of Scope
JavaScript commonly has these scope categories:
A. Global Scope
A variable declared outside functions and blocks belongs to the surrounding global scope.
It can be accessed from functions and nested blocks within that script.
const company = "Google";
function displayCompany() {
console.log(company);
}
displayCompany(); // Google
console.log(company); // Google
Here:
companyis declared in global scope.displayCompany()can access it.The global code can also access it.
B. Function Scope
A function creates its own scope.
Variables declared using var, let, and const inside a function cannot normally be accessed outside that function.
function employeeDetails() {
const employee = "Alex";
let salary = 50000;
console.log(employee);
console.log(salary);
}
employeeDetails();
console.log(employee); // ReferenceError
console.log(salary); // ReferenceError
Why?
Because employee and salary belong to the employeeDetails() function's scope.
C. Block Scope
A block is a section of code enclosed by curly braces that forms a lexical scope.
Examples include blocks associated with if, for, and standalone block statements.
Variables declared with let and const are block-scoped.
{
let city = "Delhi";
const country = "India";
console.log(city); // Delhi
console.log(country); // India
}
console.log(city); // ReferenceError
The variables are accessible inside the block, but not outside it.
D. Understanding var vs let vs const
This is one of the most important differences in JavaScript.
if (true) {
var a = 10;
let b = 20;
const c = 30;
}
console.log(a); // 10
console.log(b); // ReferenceError
console.log(c); // ReferenceError
Why does this happen?
varis function-scoped (or global-scoped when declared at the top level of a classic script).letis block-scoped.constis block-scoped.
var does not respect the if block boundary, whereas let and const do.
Declaration | Scope | Reassignment |
|---|---|---|
| Function | Yes |
| Block | Yes |
| Block | No |
Note: const prevents reassignment of the binding. It does not make objects or arrays immutable.
3. What is Lexical Scope?
Lexical scope means that JavaScript determines variable accessibility based on where functions and blocks are written in the source code.
It does not depend on where a function is called.
Consider:
const name = "Global";
function outer() {
const name = "Outer";
function inner() {
const name = "Inner";
console.log(name);
}
inner();
}
outer();
Output:
Inner
Why?
Because JavaScript first checks the current scope.
It finds name inside inner(), so it uses that value.
It doesn't need to search the outer scopes.
This is called variable shadowing: an inner declaration hides an outer declaration with the same name.
4. What is the Scope Chain?
The scope chain is the mechanism JavaScript uses to resolve identifiers by looking through the current lexical environment and its outer lexical environments.
Think of it as searching through a hierarchy.
Example:
const country = "India";
function stateOffice() {
const state = "Uttar Pradesh";
function cityOffice() {
const city = "Noida";
console.log(city);
console.log(state);
console.log(country);
}
cityOffice();
}
stateOffice();
Output:
Noida
Uttar Pradesh
India
How does JavaScript find these variables?
When cityOffice() accesses country, JavaScript searches:
Current scope (
cityOffice) — not found.Parent scope (
stateOffice) — not found.Global scope — found!
The value is returned.
This outward search is known as the scope chain lookup.
What happens when a variable cannot be found?
function test() {
console.log(username);
}
test();
Output:
ReferenceError: username is not defined
JavaScript searches the available lexical environments. If it cannot resolve the identifier, it throws a ReferenceError.
Important: Scope Chain Is Based on Where a Function Is Defined
Consider this example:
const message = "Global message";
function first() {
const message = "First function";
return second();
}
function second() {
console.log(message);
}
first();
Output:
Global message
Why not First function?
Because second() was defined in global scope, not inside first().
Although second() is called from first(), its lexical parent remains the global scope.
Remember:
Where a function is defined determines its lexical scope.
Where a function is called determines the current execution flow.
These are two different concepts.

5. What is Hoisting?
Hoisting describes how JavaScript processes declarations before executing statements in their scope.
In simple words:
JavaScript establishes variable and function bindings before executing the code line by line.
This explains why some variables and functions can be referenced before their declaration appears in the source code.
However, different declarations behave differently.
Important: Hoisting is a conceptual description of JavaScript's declaration-instantiation behavior. JavaScript does not physically move your code to the top.
6. Understanding JavaScript Execution Phases
When JavaScript evaluates a script or function, it establishes the relevant execution context and its bindings.
For learning purposes, we can understand this through two phases:
Phase 1: Memory Creation / Declaration Instantiation
JavaScript prepares bindings for declarations.
For example:
var name = "Alex";
function greet() {
console.log("Hello");
}
Conceptually, before executing the statements:
Identifier | Initial state |
|---|---|
|
|
| Function object |
The function declaration is available with its function value.
Phase 2: Code Execution
JavaScript executes statements in their normal order.
namereceives"Alex".The function can be called.
Expressions and assignments execute when reached.
These two phases are a useful learning model, not a claim that every JavaScript declaration is initialized identically.
7. Hoisting with var
Consider:
console.log(x);
var x = 7;
console.log(x);
Output:
undefined
7
Why?
During declaration instantiation, the var binding is created and initialized with undefined.
The assignment to 7 happens only when execution reaches that statement.
We can understand this using the following conceptual equivalent:
var x;
console.log(x); // undefined
x = 7;
console.log(x); // 7
Remember: The declaration is processed before execution, but the assignment is not moved.
8. Hoisting with Function Declarations
Consider:
getName();
function getName() {
console.log("Namaste JavaScript");
}
Output:
Namaste JavaScript
Why does this work?
Because a function declaration is instantiated with its function object before the statements execute.
Therefore, JavaScript can call it before its written position.
console.log(getName);
function getName() {
console.log("Namaste JavaScript");
}
Output:
ƒ getName() {
console.log("Namaste JavaScript");
}
The exact console representation depends on the JavaScript environment.
9. Hoisting with Function Expressions
Now consider:
getName();
var getName = function () {
console.log("Namaste JavaScript");
};
Output:
TypeError: getName is not a function
Why?
Because getName is declared using var.
During declaration instantiation:
getName = undefined;
The function expression is assigned to getName only when execution reaches the assignment statement.
But JavaScript encounters getName() first.
It attempts to call undefined as a function, resulting in a TypeError.
Conceptual equivalent:
var getName;
getName(); // TypeError
getName = function () {
console.log("Namaste JavaScript");
};
Important Difference
Function declaration | Function expression assigned to var |
|---|---|
Function object available during instantiation | Variable initialized to |
Can be called before its written position | Cannot be called before assignment |
Fully available within its applicable scope | Depends on when the assignment executes |
10. Hoisting with let and const
What happens here?
console.log(a);
let a = 10;
Output:
ReferenceError:
Cannot access 'a' before initialization
Does that mean let and const are not hoisted?
The more accurate explanation is that their bindings are established when the lexical environment is created, but they remain uninitialized until execution reaches their declarations.
This period is called the Temporal Dead Zone (TDZ).
Example:
{
// TDZ begins
console.log(a); // ReferenceError
let a = 10; // TDZ ends
console.log(a); // 10
}
The same principle applies to const.
Understanding TDZ
TDZ means the period between entering a lexical scope and executing the declaration that initializes a let, const, or class binding.
During this period, accessing that variable throws a ReferenceError.
Hoisting Comparison
Declaration | Before declaration |
|---|---|
| Returns |
| ReferenceError (TDZ) |
| ReferenceError (TDZ) |
Function declaration | Can be called |
Function expression assigned to | TypeError if called before assignment |

11. What Happens When a Function Is Called?
Every time a function is called, JavaScript creates a new function execution context.
An execution context is the environment in which JavaScript evaluates code and keeps track of relevant bindings, execution state, and other information.
Let's understand it through an example.
var x = 1;
function a() {
var x = 10;
console.log(x);
}
function b() {
var x = 100;
console.log(x);
}
a();
b();
console.log(x);
Output:
10
100
1
Why are three different values printed?
Because each x belongs to a different scope.
Location | Variable | Value |
|---|---|---|
Global scope |
| 1 |
Function |
| 10 |
Function |
| 100 |
The variables have the same name but belong to different lexical environments.
They do not overwrite one another.
12. Understanding Execution Context Step by Step
Let's follow the execution.
Step 1: Global Execution Context is Created
JavaScript starts evaluating the script.
A Global Execution Context (GEC) is established.
Conceptually, it contains information about the global code and its bindings.
Step 2: Declaration Instantiation
Before executing the statements:
var x = 1;
function a() {
var x = 10;
}
function b() {
var x = 100;
}
The global bindings are prepared:
Identifier | Initial state |
|---|---|
|
|
| Function object |
| Function object |
Step 3: Global Code Execution Begins
JavaScript executes:
var x = 1;
Now the global x becomes 1.
Step 4: Function a() Is Called
JavaScript creates a new execution context for a().
Its local binding is prepared:
var x = 10;
Initially, its x is undefined.
During execution, it becomes 10.
Then:
console.log(x);
Prints:
10
After the function returns, its execution context is popped from the call stack.
Step 5: Function b() Is Called
The same process happens again.
A separate execution context is created for b().
Its local x is initialized and assigned 100.
Output:
100
After the function returns, its execution context is popped from the call stack.
Step 6: Global Code Continues
Finally:
console.log(x);
The global x is still 1.
Output:
1
The global binding was never changed by the local variables inside a() or b().
13. Understanding the Call Stack
The call stack keeps track of currently executing execution contexts.
It follows LIFO (Last In, First Out).
Consider:
function first() {
second();
}
function second() {
console.log("Hello JavaScript");
}
first();
The call stack changes conceptually like this:
Operation | Call Stack |
|---|---|
Script starts | GEC |
| GEC → first |
| GEC → first → second |
| GEC → first |
| GEC |
The topmost execution context is the one currently executing.
When a function finishes, its context is removed from the active execution stack.
Important: The call stack and scope chain are different concepts.
Call stack: Tracks function execution and return order.
Scope chain: Determines where identifiers are searched.

Important Concepts and Interview Traps
14. Variable Shadowing
When an inner scope declares a variable with the same name as an outer scope variable, the inner variable shadows the outer variable.
let name = "Global";
function test() {
let name = "Local";
console.log(name);
}
test();
console.log(name);
Output:
Local
Global
The local declaration hides the outer declaration only within its scope.
15. Accidental Global Variables
Consider:
function test() {
count = 10;
}
test();
console.log(count);
In non-strict classic script code, assigning to an undeclared identifier can create a property on the global object.
In strict mode, it throws a ReferenceError.
Use:
"use strict";
function test() {
let count = 10;
}
Modern JavaScript modules are automatically strict mode.
Always declare variables explicitly.
16. Does a Function Lose Its Variables After Execution?
Normally, a function's execution context is removed from the active call stack after it returns.
However, its lexical environment may remain reachable if a closure still references it.
Example:
function outer() {
let count = 0;
function inner() {
count++;
console.log(count);
}
return inner;
}
const counter = outer();
counter(); // 1
counter(); // 2
counter(); // 3
Even after outer() returns, inner() can still access count.
Why?
Because the returned function retains access to its surrounding lexical environment.
This is called a Closure.
We will study closures in a separate chapter.
30-Second Quick Revision
Scope
Scope determines where identifiers can be accessed.
Global scope is available throughout its applicable global code.
Function scope is created by functions.
Block scope is created by lexical blocks.
varis function-scoped.letandconstare block-scoped.
Scope Chain
JavaScript searches the current lexical environment first.
If the identifier is not found, it searches outward.
Inner scopes can access outer scopes.
Outer scopes cannot access variables exclusive to inner scopes.
Lexical scope depends on where a function is defined, not where it is called.
Hoisting
Declarations are processed before normal statement execution.
varbindings are initialized withundefined.Function declarations are available before their written position.
Function expressions depend on when their assignment executes.
letandconstcannot be accessed during the TDZ.
Execution Context
JavaScript creates execution contexts to evaluate code.
A function call creates a new function execution context.
The call stack tracks active execution contexts.
Each function has its own local bindings.
A returned function can retain access to its lexical environment through closures.
Interview Practice
Try answering these without looking at the explanations.
Question 1: Scope
let a = 10;
function test() {
let a = 20;
console.log(a);
}
test();
console.log(a);
What is the output?
Question 2: Scope Chain
let x = 100;
function outer() {
let y = 200;
function inner() {
console.log(x, y);
}
inner();
}
outer();
How does JavaScript resolve x and y?
Question 3: Hoisting
console.log(a);
var a = 10;
console.log(a);
What is the output and why?
Question 4: Temporal Dead Zone
console.log(a);
let a = 10;
Why does this produce a ReferenceError instead of undefined?
Question 5: Function Hoisting
greet();
function greet() {
console.log("Hello");
}
Why does this work?
Question 6: Function Expression
greet();
var greet = function () {
console.log("Hello");
};
Why does this produce a TypeError?
Question 7: Variable Environments
var x = 1;
function first() {
var x = 2;
second();
}
function second() {
console.log(x);
}
first();
Will it print 1 or 2? Explain using lexical scope.