LATEST 🚀 Welcome to Upgradix by Shrash Studio – Your destination for free technology learning and career growth.
🕘 Updated:
JavaScript

Scope and Hoisting in JavaScript – Global, Function and Block Scope

Hoisting describes how JavaScript processes declarations before executing the code. These concepts help us understand why some variables work in one place but cause errors in another. They are important when writing functions, working with blocks, and debugging applications.

Scope and Hoisting in JavaScript – Understand Global, Function and Block Scope

Quick Answer: Scope decides where JavaScript variables can be accessed. JavaScript has global, function and block scope. Hoisting describes how JavaScript processes declarations before running code. Function declarations, var, let and const behave differently during this process.

1. Why Do Scope and Hoisting Matter?

Imagine you manage a school with 1,000 students. Each student has marks, attendance and personal details. Teachers also have their own classroom information. The school office maintains information for everyone.

What happens when every teacher uses the same variable names? What happens when a teacher accesses a value before declaring it?

Think about these situations before looking at the solution.

The Problem: Keeping Every Variable in One Shared Space

JavaScript allows us to create variables without thinking about their boundaries. This can make larger programs difficult to manage.

Example 1: A School Using Shared Variables

This example uses global variables for different student records.

var studentName = "Priya";
var studentMarks = 85;

function showFirstStudent() {
  var studentName = "Ravi";
  console.log(studentName);
}

function showSecondStudent() {
  studentName = "Lakshmi";
  console.log(studentName);
}

showFirstStudent();
showSecondStudent();
console.log(studentMarks);
console.log(studentName);

Expected output

Ravi
Lakshmi
85
Lakshmi

This code runs, but its variables are difficult to manage. The second function changes the shared student name.

What Goes Wrong?

  1. Shared values: One function can change data used by another function.
  2. Unclear boundaries: It becomes harder to know where a variable belongs.
  3. Unexpected access: A variable may not be available where we expect it.
  4. Declaration confusion: Using variables before their declarations can produce different results.
  5. Maintenance risk: Small changes can affect unrelated parts of the application.

Now think about hundreds of teachers and thousands of student records. Clear variable boundaries become important.

Without Scope and Hoisting Knowledge vs With It

How scope and hoisting knowledge improves JavaScript code
Without understanding With understanding
Variables are placed without clear boundaries. Variables are declared in the correct scope.
Functions may change shared values unexpectedly. Function variables stay inside their functions.
Block variables may be accessed incorrectly. Block variables stay inside their blocks.
Declarations before use can be confusing. Hoisting behavior is understood and handled safely.

The Idea to Remember

  • Scope = the area where a variable can be accessed.
  • Global scope = an area available across the relevant program context.
  • Function scope = an area limited to a function.
  • Block scope = an area limited to a block marked by braces.
  • Hoisting = JavaScript's declaration processing before execution.
  • Temporal Dead Zone = the time before a let or const declaration is initialized.

2. What Is Scope in JavaScript?

Scope decides where a variable can be used in your code. It controls variable visibility and access.

JavaScript mainly uses three scope types:

Global scope

A variable can be accessed across its relevant program context.

Function scope

A variable declared inside a function belongs to that function.

Block scope

A variable declared with let or const belongs to its block.

Lexical scope

Inner functions can access variables from their surrounding scopes.

3. Global Scope in JavaScript

A global variable is declared outside functions and blocks. Code in its accessible program context can use it.

For our school example, the school name can be shared across several functions.

Example 2: Accessing a Global Variable

const schoolName = "Green Valley School";

function showSchoolName() {
  console.log(schoolName);
}

function showAdmissionMessage() {
  console.log("Welcome to " + schoolName);
}

showSchoolName();
showAdmissionMessage();

Expected output

Green Valley School
Welcome to Green Valley School

How Does This Work?

  • schoolName is declared outside both functions.
  • Both functions can access the same global binding.
  • The variable is not declared again inside either function.
  • Using const prevents reassignment of this binding.

Important: Global scope depends on how JavaScript runs your code. Browser scripts and JavaScript modules have different global behavior. A top-level module variable does not become a property of window.

Global Variables in Browser JavaScript

In a classic browser script, a top-level var declaration creates a property on the global object. A top-level let or const declaration does not.

Example 3: Global Object Behavior in a Classic Browser Script

var schoolCode = "SCH101";
let academicYear = "2026-27";

console.log(window.schoolCode);
console.log(window.academicYear);

Expected output in a classic browser script

SCH101
undefined

This example assumes a classic browser script. It is not a JavaScript module.

4. Function Scope in JavaScript

Function scope means a variable belongs to the function where it is declared. Other functions cannot directly access that local variable.

The var keyword uses function scope. The let and const keywords also work inside functions, but they follow block scope rules too.

Example 4: Student Details Inside a Function

function showStudentDetails() {
  var studentName = "Priya";
  let studentMarks = 85;

  console.log(studentName);
  console.log(studentMarks);
}

showStudentDetails();

console.log("Student details displayed");

Expected output

Priya
85
Student details displayed

Both variables belong to the function. They cannot be accessed directly outside it.

What Happens When We Access a Function Variable Outside?

Example 5: Trying to Access a Local Variable

function showStudentDetails() {
  let studentName = "Priya";
  console.log(studentName);
}

showStudentDetails();

console.log(studentName);

Expected behavior: The last statement throws a ReferenceError. The variable is not available outside the function.

Function Scope Animation: School Record Boundaries

Where does each student value belong?

The highlighted area shows the current scope boundary.

Global scope · School office
schoolName Green Valley
Function scope · Teacher's report
studentName Priya studentMarks 85
Block scope · Attendance check
isPresent true
● Blue: global ● Purple: function ● Green: block

The animation moves through nested school scopes. Each variable belongs to its declared area.

5. Block Scope in JavaScript

A block is a group of statements inside curly braces. Examples include if, for and standalone brace blocks.

let and const create block-scoped variables. A variable declared inside a block cannot be accessed outside it.

Example 6: Variables Inside an If Block

let studentName = "Ravi";

if (true) {
  let studentMarks = 90;
  const result = "Passed";

  console.log(studentName);
  console.log(studentMarks);
  console.log(result);
}

console.log(studentName);

Expected output

Ravi
90
Passed
Ravi

The outer variable is available inside the block. The block variables stay inside it.

What Happens When We Use var Inside a Block?

The var keyword does not create block scope. Its variable belongs to the nearest function scope or global context.

Example 7: var Can Escape an If Block

if (true) {
  var studentMarks = 90;
  let attendance = "Present";
}

console.log(studentMarks);
console.log(attendance);

Expected behavior: The first log prints 90. The second log throws a ReferenceError.

The var variable remains accessible outside the block. The let variable does not.

Block Scope Animation: Inside vs Outside

The block boundary controls access

Watch how the attendance value stays inside its block.

Outside block studentName = "Ravi"
Inside block attendance = "Present"
↓
Inside block: attendance is available

Outside the block, the attendance variable cannot be accessed.

The green block represents a local boundary. Its variable remains available only inside that boundary.

6. What Is Lexical Scope?

Lexical scope means inner functions can access variables from their surrounding code. JavaScript decides this from where functions are written, not where they are called.

Consider a teacher report function inside a school function. The inner function can access the school name.

Example 8: An Inner Function Accessing an Outer Variable

function schoolReport() {
  const schoolName = "Green Valley School";

  function showReport() {
    const studentName = "Priya";

    console.log(schoolName);
    console.log(studentName);
  }

  showReport();
}

schoolReport();

Expected output

Green Valley School
Priya

Can the Outer Function Access the Inner Variable?

No. Scope works from the inner function towards its surrounding scopes. The outer function cannot directly access a variable declared inside the inner function.

Example 9: Inner Variables Are Not Available Outside

function schoolReport() {
  function showReport() {
    const studentName = "Priya";
    console.log(studentName);
  }

  showReport();
  console.log(studentName);
}

schoolReport();

Expected behavior: The first log prints Priya. The second log throws a ReferenceError.

7. What Is Hoisting in JavaScript?

Hoisting describes how JavaScript processes declarations before executing code. It does not mean JavaScript physically moves your code.

Different declarations have different hoisting behavior. This difference is important during interviews and debugging.

Understanding Hoisting with a Simple Example

Look at this code. We access a variable before its declaration.

Example 10: Accessing a var Variable Before Declaration

console.log(schoolName);

var schoolName = "Green Valley School";

console.log(schoolName);

Expected output

undefined
Green Valley School

JavaScript processes the var declaration before execution. Its initial value is undefined.

The assignment still happens at its original position. That is why the first log prints undefined.

Hoisting Execution Timeline

How JavaScript handles a var declaration

Four stages show declaration processing and execution.

1
Read the declaration

JavaScript identifies the variable declaration.

2
Create the binding

The var binding is created and initialized with undefined.

3
Execute the first log

The variable still contains undefined.

4
Run the assignment

The school name is assigned. The next log shows it.

The timeline highlights declaration setup first, followed by normal statement execution.

8. Hoisting with var, let and const

All three declarations are processed before normal execution. Their initialization rules are different.

Hoisting with var

A var declaration is initialized with undefined. You can read it before its assignment.

Example 11: var Hoisting

console.log(studentMarks);

var studentMarks = 85;

console.log(studentMarks);

Expected output

undefined
85

Hoisting with let

A let declaration is hoisted but remains uninitialized. Accessing it before its declaration throws a ReferenceError.

Example 12: let and the Temporal Dead Zone

console.log(studentMarks);

let studentMarks = 85;

Expected behavior: JavaScript throws a ReferenceError on the first line. The assignment is never reached.

Hoisting with const

A const declaration also stays uninitialized until its declaration runs. Accessing it too early throws a ReferenceError.

Example 13: const and the Temporal Dead Zone

console.log(schoolName);

const schoolName = "Green Valley School";

Expected behavior: JavaScript throws a ReferenceError on the first line.

var vs let vs const: Hoisting Comparison

Declaration and initialization behavior
Keyword Hoisted Initial state Access before declaration
var Yes undefined Returns undefined
let Yes Uninitialized ReferenceError
const Yes Uninitialized ReferenceError

Remember: Saying that let and const are not hoisted is incorrect. They are hoisted, but cannot be accessed before initialization.

9. Function Declaration Hoisting

Function declarations are hoisted with their function body. This allows us to call them before their declaration.

Example 14: Calling a Function Before Its Declaration

showAdmissionMessage();

function showAdmissionMessage() {
  console.log("Admission is open");
}

Expected output

Admission is open

The function declaration is available before its line executes. JavaScript can call it successfully.

Function Expression Hoisting

A function expression behaves differently. Its variable declaration follows the keyword's hoisting rules.

Example 15: Function Expression with var

showAdmissionMessage();

var showAdmissionMessage = function() {
  console.log("Admission is open");
};

Expected behavior: JavaScript throws a TypeError. The variable exists, but its value is still undefined when called.

Example 16: Function Expression with let

showAdmissionMessage();

let showAdmissionMessage = function() {
  console.log("Admission is open");
};

Expected behavior: JavaScript throws a ReferenceError. The variable is still in its Temporal Dead Zone.

Function Declaration vs Function Expression

How different function forms behave
Declaration type Hoisting behavior Can call before declaration?
Function declaration Function is available Yes
Function expression with var Variable starts as undefined No
Function expression with let Variable is uninitialized No
Function expression with const Variable is uninitialized No

10. The Temporal Dead Zone Explained

The Temporal Dead Zone is often called the TDZ. It is the period between entering a scope and initializing a let or const binding.

During this period, accessing that variable throws a ReferenceError.

Example 17: Understanding the TDZ

{
  // The TDZ starts when this block is entered.

  console.log(studentName);

  let studentName = "Priya";

  // The TDZ ends after initialization.
  console.log(studentName);
}

Expected behavior: The first log throws a ReferenceError. The second log is not reached.

The TDZ does not mean the variable is missing. Its binding exists but is not ready for access.

How to Avoid TDZ Errors

  • Declare variables before using them.
  • Keep declarations near the code that uses them.
  • Use const by default when reassignment is unnecessary.
  • Use let when a value must change.
  • Avoid relying on hoisting for normal program flow.

11. Scope Chain in JavaScript

When JavaScript cannot find a variable locally, it checks the surrounding scope. It continues outward until it finds the variable or reaches the global scope.

This lookup process is called the scope chain.

Example 18: JavaScript Searches Outer Scopes

const schoolName = "Green Valley School";

function showClassReport() {
  const className = "Class 10";

  function showStudentReport() {
    const studentName = "Priya";

    console.log(studentName);
    console.log(className);
    console.log(schoolName);
  }

  showStudentReport();
}

showClassReport();

Expected output

Priya
Class 10
Green Valley School

How Variable Lookup Works

  1. JavaScript first checks the current function scope.
  2. If missing, it checks the surrounding function scope.
  3. It continues checking outer lexical scopes.
  4. It finally checks the global environment.
  5. If no binding exists, JavaScript throws a ReferenceError.

Scope chain: finding the school name

The lookup starts inside the student report and moves outward.

Global scope
schoolName Green Valley
Outer function · Class report
className Class 10
Inner function · Student report
studentName Priya

The inner function can read its own variables and values from outer scopes.

The nested layers represent lexical lookup. JavaScript searches outward when a local binding is not found.

12. Common Mistakes and Best Practices

Mistake 1: Using var When Block Scope Is Needed

Wrong approach: Declaring a loop variable with var when you expect it to stay inside the loop.

Wrong Example

for (var index = 0; index < 3; index++) {
  console.log(index);
}

console.log(index);

Output

0
1
2
3

Better approach: Use let for a loop variable that should stay inside the loop.

Correct Example

for (let index = 0; index < 3; index++) {
  console.log(index);
}

Output

0
1
2

Mistake 2: Assuming let Is Not Hoisted

Wrong assumption: JavaScript does not process a let declaration before its line.

Correct understanding: The binding exists, but remains uninitialized until the declaration runs. Accessing it early throws a ReferenceError.

Mistake 3: Calling a Function Expression Too Early

Wrong approach: Calling a variable that has not received its function value.

Better approach: Assign the function before calling it.

Correct Example

const showAdmissionMessage = function() {
  console.log("Admission is open");
};

showAdmissionMessage();

Output

Admission is open

Mistake 4: Creating Too Many Global Variables

Wrong approach: Keeping every application value in global scope.

Better approach: Keep values inside the function or module that owns them. Expose only the values other code needs.

Mistake 5: Confusing Scope with Hoisting

Scope controls where a variable can be accessed. Hoisting controls how declarations are processed before execution.

They are related JavaScript concepts, but they solve different problems.

Best Practices Checklist

  • Prefer const when reassignment is not needed.
  • Use let when a variable must be reassigned.
  • Avoid var in modern JavaScript code.
  • Keep variables close to where they are used.
  • Limit global variables to genuinely shared values.
  • Declare variables before accessing them.
  • Use function declarations when early function calls are intentional.
  • Understand module scope when building larger applications.

13. How Scope and Hoisting Work in Real Projects

Scope and hoisting matter in browser applications, Node.js services and frontend frameworks.

In Frontend Applications

  • Block scope helps keep loop and condition variables local.
  • Function scope helps separate logic into smaller units.
  • Module scope keeps implementation details private to a module.
  • Lexical scope supports closures and callback functions.

In Node.js Applications

  • Each CommonJS module has its own module-level scope.
  • ES modules have their own module scope.
  • Top-level module declarations do not become global object properties.
  • Closures can retain values after an outer function returns.

Why Closures Matter

A closure is a function that remembers variables from its surrounding scope. The outer function can finish, but the inner function can still use those variables.

Example 19: A Closure for Student Marks

function createStudentRecord(studentName) {
  let studentMarks = 0;

  return function(newMarks) {
    studentMarks = newMarks;
    console.log(studentName + ": " + studentMarks);
  };
}

const updatePriyaMarks = createStudentRecord("Priya");

updatePriyaMarks(85);
updatePriyaMarks(92);

Expected output

Priya: 85
Priya: 92

The returned function remembers both variables. Each call updates the same private marks value.

Architect's note: Closures are useful for private state and callbacks. Be careful with long-lived closures that retain large objects unnecessarily.

14. Interview Questions and Answers

Q1. What is scope in JavaScript?

What the interviewer wants: They want to know how you understand variable access.

Strong answer: "Scope decides where a variable can be accessed. JavaScript has global, function and block scope. Inner functions can also access variables from their outer scopes through lexical scope."

Q2. What is hoisting in JavaScript?

Strong answer: "Hoisting describes how JavaScript processes declarations before executing code. A var variable starts as undefined. Let and const stay uninitialized until their declarations run. Function declarations are available before their declaration lines."

Q3. What is the difference between var, let and const?

Strong answer: "Var is function-scoped and can be redeclared. Let and const are block-scoped. Let allows reassignment, while const does not allow reassignment. Both let and const have a Temporal Dead Zone before initialization."

Q4. Are let and const hoisted?

Strong answer: "Yes, both are hoisted. Their bindings are created before execution. However, they are not initialized immediately. Accessing them before initialization causes a ReferenceError."

Q5. What is the Temporal Dead Zone?

Strong answer: "The Temporal Dead Zone is the time before a let or const declaration is initialized. The variable cannot be accessed during this period. Accessing it causes a ReferenceError."

Q6. What is the difference between function declarations and expressions?

Strong answer: "A function declaration is available before its declaration line. A function expression depends on its variable declaration. Calling it too early can produce a TypeError or ReferenceError."

Q7. What is lexical scope?

Strong answer: "Lexical scope means an inner function can access variables from its surrounding code. JavaScript determines this from where the function is written. This behavior also supports closures."

Q8. What is the scope chain?

Strong answer: "The scope chain is the lookup process used to find variables. JavaScript checks the current scope first. It then checks outer scopes until it finds the variable or reaches the global environment."

What Should Different Experience Levels Explain?

Interview expectations by experience level
Level Expected understanding
Junior Explain global, function and block scope with simple examples.
Mid-level Explain hoisting, TDZ, closures and common declaration mistakes.
Senior Explain lexical environments, modules and practical debugging cases.
Architect Explain module boundaries, state ownership and maintainable application design.

15. Hands-On Practice

Beginner Exercise 1: Identify the Scope

Read the code and identify which variables are accessible outside the block.

Exercise Code

const schoolName = "Green Valley School";

if (true) {
  let studentName = "Priya";
  var studentMarks = 85;
}

console.log(schoolName);
console.log(studentMarks);
console.log(studentName);

Hint: Check the declaration keyword for each variable. Remember that var does not follow block scope.

Beginner Exercise 2: Predict the Output

What does the first log print?

Exercise Code

console.log(studentMarks);

var studentMarks = 95;

console.log(studentMarks);

Hint: Remember the initial value of a hoisted var declaration.

Intermediate Exercise 3: Fix the TDZ Error

Correct this code without removing the variable.

Exercise Code

console.log(schoolName);

const schoolName = "Green Valley School";

Hint: Move the variable access after initialization.

Intermediate Exercise 4: Understand Function Scope

Change the code so the student name can be accessed safely outside the function.

Exercise Code

function getStudentName() {
  const studentName = "Ravi";
}

getStudentName();
console.log(studentName);

Hint: Return the value from the function. Store the returned value in another variable.

Advanced Exercise 5: Build a Private Student Record

Create a function that accepts a student name. It should return another function that updates marks. Keep the marks variable private.

Expected behavior: Updating one student's marks must not change another student's record.

Advanced Exercise 6: Explain the Function Output

Predict the output and explain why the inner function uses the outer value.

Exercise Code

const className = "Class 10";

function showClass() {
  const className = "Class 12";

  function showStudent() {
    console.log(className);
  }

  showStudent();
}

showClass();

Hint: JavaScript uses lexical scope. The inner function finds the nearest matching variable.

16. Frequently Asked Questions

Is hoisting the same as moving code to the top?

No. Hoisting is a way to describe declaration processing. JavaScript does not physically move your source code.

Can we access a var variable before declaration?

Yes. Its declaration is processed first, and its initial value is undefined. Its assignment still happens at its original position.

Can we access let before declaration?

No. The binding exists, but it is uninitialized. Accessing it during the Temporal Dead Zone throws a ReferenceError.

Does const prevent changes to objects?

No. Const prevents reassignment of the variable binding. Object properties can still change unless you use additional protection.

Does a block create function scope?

No. A block creates block scope for let and const. A function creates its own function scope.

Are function expressions hoisted?

The variable holding the expression follows its declaration rules. The function value is assigned when execution reaches the expression.

Which keyword should we use in modern JavaScript?

Prefer const when reassignment is unnecessary. Use let when the value must change. Avoid var in new code unless a specific legacy behavior is needed.

17. Next Steps and Community

Try It Yourself

Open your browser developer tools and try every example. Change the declaration keywords and observe the results. Test each example separately when it throws an error.

Explore Further

  • MDN: Scope – Learn how JavaScript controls variable access.
  • MDN: Hoisting – Understand declaration processing.
  • MDN: Closures – Explore lexical scope in more detail.
  • MDN: let – Learn about block scope and the Temporal Dead Zone.
  • MDN: const – Understand constant bindings.

Share Your Knowledge

Try the exercises and share your solutions with the developer community. Explain any unexpected output you discover. Help other learners understand scope and hoisting with your own examples.

Key Takeaway: Scope controls where variables are available. Hoisting explains how declarations are processed before execution. Understand both concepts to write predictable and maintainable JavaScript.

Upgradix by Shrash Studio — Learn Technology. Build Your Future.

Quality Technology Education. Completely Free.

Comments & Ratings (0)

Log in or create a student account to comment and rate this article.

Be the first to comment on this article.