JavaScript Scope and Hoisting: Global, Function, Block and Lexical Scope
Every variable lives somewhere. Scope decides where a name can be used, and hoisting decides what happens when you use a name before the line that declares it. Together they explain many confusing bugs: a variable that is “not defined” inside a callback, a value that changes when it should not, or undefined appearing out of nowhere. In this lesson you will learn every kind of scope, how JavaScript looks names up through the scope chain, and exactly what is hoisted and what is not.
📖 What You’ll Learn: what scope is, global, module, function and block scope, the scope chain and lexical scope, shadowing, how hoisting works for var, let, const, function declarations, function expressions and classes, the temporal dead zone, and how to avoid scope bugs in tests.
🗺️ What Is Scope?
Definition: the scope of a variable is the region of code where that variable can be accessed. Outside its scope the name does not exist, and using it throws a ReferenceError.
| Scope | Created by | Applies to |
|---|---|---|
| Global | The top level of a browser classic script | var, let, const, functions |
| Module | Each ES module or Node.js file | Everything declared at the top of that file |
| Function | Every function | var, let, const, parameters, inner functions |
| Block | Any { }: if, for, while, plain blocks | let, const, class (not var) |
Scopes are nested: a block inside a function inside a module. Inner code can see outer variables, but outer code cannot see inner variables.
🌍 Global and Module Scope
In a browser classic <script>, top-level variables are global: every other script on the page can read and change them. In Node.js and in ES modules, each file has its own module scope, so top-level variables are private to that file unless you export them.
📄 module-scope.js
const BASE_URL = "https://sqatools.in"; // module scope: visible everywhere in this file
function loginUrl() {
return `${BASE_URL}/login`; // inner code can read outer variables
}
console.log(loginUrl());
console.log(typeof globalThis.BASE_URL); // not a property of the global object
console.log(typeof globalThis.console); // built-ins are truly global
⌨️ Terminal
node module-scope.js
🖥️ Output
https://sqatools.in/login
undefined
object
⚠️ Watch out: Assigning to an undeclared name in sloppy mode creates an accidental global (see the Syntax lesson). Strict mode and ES modules turn that into a ReferenceError.
🏠 Function Scope
Variables declared inside a function, including its parameters, exist only while that function runs and only inside it:
📄 function-scope.js
function checkout(cartTotal) {
const tax = cartTotal * 0.18;
var shipping = 50;
return cartTotal + tax + shipping;
}
console.log(checkout(1000));
console.log(typeof tax, typeof shipping, typeof cartTotal);
console.log(tax);
⌨️ Terminal
node function-scope.js
🖥️ Output
1230
undefined undefined undefined
/home/you/js-course/function-scope.js:9
console.log(tax);
^
ReferenceError: tax is not defined
at Object.<anonymous> (/home/you/js-course/function-scope.js:9:13)
Node.js v26.13.0
typeof is safe to use on unknown names and returns "undefined"; using the name directly throws. Each call also gets a fresh set of local variables, so two calls never share their locals.
🧱 Block Scope
let, const and class are scoped to the nearest block { }. var ignores blocks and belongs to the whole function (or file).
📄 block-scope.js
function report(results) {
for (let i = 0; i < results.length; i++) {
const line = `${i + 1}. ${results[i]}`;
var lastLine = line;
console.log(line);
}
console.log("after loop, lastLine:", lastLine); // var leaked out of the block
console.log("i is", typeof i, "- line is", typeof line);
}
report(["login passed", "search failed"]);
⌨️ Terminal
node block-scope.js
🖥️ Output
1. login passed
2. search failed
after loop, lastLine: 2. search failed
i is undefined - line is undefined
You can also create a plain block just to limit a variable’s lifetime:
📄 plain-block.js
{
const temp = "only needed here";
console.log(temp);
}
console.log(typeof temp);
⌨️ Terminal
node plain-block.js
🖥️ Output
only needed here
undefined
🔍 The Scope Chain and Lexical Scope
Definition: when JavaScript looks up a name, it searches the current scope first, then the enclosing scope, and so on outwards until the module or global scope. This chain of nested scopes is the scope chain. If the name is not found anywhere, you get a ReferenceError.
Lexical scope means the chain is decided by where the code is written, not by where a function is called from:
📄 lexical.js
const env = "module";
function outer() {
const env = "outer";
function inner() {
return `inner sees ${env}`; // looks up: inner -> outer (found)
}
return inner;
}
function caller() {
const env = "caller";
const fn = outer();
return fn(); // called from caller, but scope comes from where inner was written
}
console.log(caller());
⌨️ Terminal
node lexical.js
🖥️ Output
inner sees outer
The result is inner sees outer, not caller. This rule is what makes closures work, which is the subject of the next lesson.
🎭 Shadowing
Definition: shadowing happens when an inner scope declares a variable with the same name as an outer one. Inside the inner scope, the inner variable hides the outer one.
📄 shadowing.js
const status = "global status";
function runTest() {
const status = "test status"; // shadows the outer status
if (true) {
const status = "block status"; // shadows again
console.log(status);
}
console.log(status);
}
runTest();
console.log(status);
⌨️ Terminal
node shadowing.js
🖥️ Output
block status
test status
global status
💡 Tip: Shadowing is legal but makes code harder to follow, especially with short names like data or result. ESLint’s no-shadow rule can warn you.
⬆️ Hoisting: What Is Moved to the Top?
Definition: before running a scope, JavaScript registers all declarations in it. This is hoisting. What you can do before the declaration line depends on the kind of declaration:
| Declaration | Hoisted? | Value before its line |
|---|---|---|
function f() {} | Yes, with body | The function: callable |
var x | Yes | undefined |
let x / const x | Yes, but uninitialised | ReferenceError (TDZ) |
class C {} | Yes, but uninitialised | ReferenceError (TDZ) |
const f = function () {} / arrow | Like its const | ReferenceError (TDZ) |
var f = function () {} | Like its var | undefined: calling it is a TypeError |
📄 hoisting.js
console.log(add(2, 3)); // function declaration: works
console.log(typeof legacy); // var: undefined, not an error
function add(a, b) {
return a + b;
}
var legacy = "set later";
try {
multiply(2, 3); // var holding a function expression
} catch (e) {
console.log(e.constructor.name + ":", e.message);
}
var multiply = function (a, b) {
return a * b;
};
try {
new Report();
} catch (e) {
console.log(e.constructor.name + ":", e.message);
}
class Report {}
⌨️ Terminal
node hoisting.js
🖥️ Output
5
undefined
TypeError: multiply is not a function
ReferenceError: Cannot access 'Report' before initialization
The temporal dead zone (TDZ) can appear inside a scope
A let in an inner scope hides the outer variable for the whole inner scope, even before its declaration line:
📄 tdz-shadow.js
const user = "outer user";
function show() {
console.log(user); // refers to the inner user, which is still in the TDZ
const user = "inner user";
}
show();
⌨️ Terminal
node tdz-shadow.js
🖥️ Output
/home/you/js-course/tdz-shadow.js:4
console.log(user); // refers to the inner user, which is still in the TDZ
^
ReferenceError: Cannot access 'user' before initialization
at show (/home/you/js-course/tdz-shadow.js:4:15)
at Object.<anonymous> (/home/you/js-course/tdz-shadow.js:8:1)
Node.js v26.13.0
Many people expect this to print outer user. Because the inner user is hoisted to the top of show, the name already refers to it, and it is not initialised yet.
🧪 Tester Scenario: Avoid Shared State Between Tests
A test file often has variables at module scope. If tests change them, the result depends on test order, which is a classic source of flaky tests. This simulation runs two “tests” in different orders:
📄 shared-state.js
// Shared, mutable module-level state (bad)
let cart = [];
const tests = {
"adds item": () => { cart.push("pen"); return cart.length === 1; },
"cart starts empty": () => cart.length === 0,
};
function runInOrder(order) {
cart = [];
return order.map((name) => `${name}: ${tests[name]() ? "PASS" : "FAIL"}`).join(", ");
}
console.log("order A:", runInOrder(["cart starts empty", "adds item"]));
console.log("order B:", runInOrder(["adds item", "cart starts empty"]));
// Fixed: each test creates its own state in its own function scope
const isolated = {
"adds item": () => { const cart = []; cart.push("pen"); return cart.length === 1; },
"cart starts empty": () => { const cart = []; return cart.length === 0; },
};
console.log("isolated:", Object.entries(isolated).map(([n, t]) => `${n}: ${t() ? "PASS" : "FAIL"}`).join(", "));
⌨️ Terminal
node shared-state.js
🖥️ Output
order A: cart starts empty: PASS, adds item: PASS
order B: adds item: PASS, cart starts empty: FAIL
isolated: adds item: PASS, cart starts empty: PASS
In Playwright, beforeEach hooks and fixtures give each test fresh state for the same reason, and they matter even more when tests run in parallel.
📝 Practice Questions with Answers
Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.
Q1. Predict what each console.log prints, then run the code.
let a = 1;
function f() {
let a = 2;
{
let a = 3;
console.log(a);
}
console.log(a);
}
f();
console.log(a);Show answer
📄 practice1.js
let a = 1;
function f() {
let a = 2;
{
let a = 3;
console.log(a);
}
console.log(a);
}
f();
console.log(a);🖥️ Output
3
2
1Each block declares its own a, shadowing the outer one only inside that block.
Q2. Explain why this prints undefined instead of throwing an error.
console.log(total);
var total = 100;Show answer
📄 practice2.js
console.log(total);
var total = 100;🖥️ Output
undefinedvar total is hoisted to the top of the scope and initialised with undefined. Only the assignment = 100 stays on its line. With let or const it would be a ReferenceError (TDZ).
Q3. Write a function counterReport() that declares a counter inside a for loop block with let, and show that the counter is not available after the loop.
Show answer
📄 practice3.js
function counterReport() {
for (let i = 0; i < 3; i++) {
// i only exists in this loop
}
return typeof i;
}
console.log(counterReport());🖥️ Output
undefinedQ4. Fix this code so it prints QA then DEV without renaming the outer variable.
const team = "QA";
function show() {
console.log(team);
const team = "DEV";
console.log(team);
}
show();Show answer
The inner team is in the temporal dead zone at the first log. Give the inner variable a different name:
📄 practice4.js
const team = "QA";
function show() {
console.log(team);
const otherTeam = "DEV";
console.log(otherTeam);
}
show();🖥️ Output
QA
DEVQ5. Which function can be called before its definition: function a() {}, const b = () => {}, var c = function () {}? Prove it with typeof before the definitions.
Show answer
📄 practice5.js
console.log(typeof a); // "function": hoisted with body
console.log(typeof c); // "undefined": var hoisted, value not yet assigned
try {
console.log(typeof b); // b is in the TDZ
} catch (e) {
console.log(e.message);
}
function a() {}
const b = () => {};
var c = function () {};🖥️ Output
function
undefined
Cannot access 'b' before initializationEven typeof throws for a name in the TDZ. Only a can be called before its definition.
Q6. Rewrite this so each call to createCounter has its own count instead of sharing a module-level one.
let count = 0;
function createCounter() {
return () => ++count;
}Show answer
📄 practice6.js
function createCounter() {
let count = 0; // each call creates a new count
return () => ++count;
}
const a = createCounter();
const b = createCounter();
console.log(a(), a(), b());🖥️ Output
1 2 1This is a closure, explained in detail in the next lesson.
🧠 MCQ Quiz: Scope and Hoisting
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- Which keywords are block-scoped?Answer: let, const and class. var is function-scoped.
- How is the scope of a variable decided in JavaScript?Answer: By where the code is written (lexical scope). JavaScript uses lexical (static) scope.
- What does
typeof undeclaredNamereturn?Answer: “undefined”. typeof is safe for names that were never declared (but not for names in the TDZ). - What is printed?
console.log(x); var x = 7;Answer: undefined. var is hoisted and initialised to undefined. - Which can be called before its line?Answer:
function go() {}. Only function declarations are hoisted with their body. - What is shadowing?Answer: An inner variable with the same name hiding an outer one. Inside the inner scope, the name refers to the inner variable.
- In Node.js, is a top-level
constin one file visible in another file?Answer: No, each file has its own module scope. Share values between files with exports and imports. - What happens when a variable is not found anywhere in the scope chain?Answer: ReferenceError: x is not defined. Reading an unknown name throws (assigning to one in sloppy mode creates a global).
- What is printed?
let v = 1; { let v = 2; } console.log(v);Answer: 1. The inner v exists only inside its block. - Why can shared module-level variables cause flaky tests?Answer: Tests that change them affect each other depending on order. Give each test its own state in hooks or fixtures.
💼 Interview Questions and Answers
Q1. What is the difference between function scope and block scope?
Function scope means a variable is visible throughout the function in which it is declared; var works this way and ignores if/for blocks. Block scope means a variable is visible only inside the nearest { }; let, const and class work this way. Block scope keeps variables short-lived and prevents leaks such as a loop counter being visible after the loop.
Q2. What is hoisting? Is let hoisted?
Hoisting is the creation of all declarations in a scope before any code in that scope runs. Function declarations are hoisted with their body; var is hoisted and initialised to undefined; let, const and class are hoisted but left uninitialised, so accessing them before the declaration throws a ReferenceError (temporal dead zone). So yes, let is hoisted, just not initialised.
Q3. What is lexical scope and the scope chain?
Lexical scope means the set of variables a piece of code can access is determined by its position in the source code. When a name is used, the engine looks in the current scope, then each enclosing scope outward, up to the module and global scope: that path is the scope chain. Where a function is called from does not matter.
Q4. Predict the output.
📄 predict.js
var x = "global";
function test() {
console.log(x);
var x = "local";
console.log(x);
}
test();
⌨️ Terminal
node predict.js
🖥️ Output
undefined
local
The inner var x is hoisted to the top of test and shadows the outer x, so the first log prints undefined, not "global". The second prints "local".
❓ Frequently Asked Questions
🤔 What are the types of scope in JavaScript?
Global scope, module scope (per file in Node.js and ES modules), function scope and block scope. Closures let inner functions keep access to outer scopes.
🤔 Are function expressions hoisted?
Only the variable that holds them is hoisted, following var, let or const rules. The function itself is created when that line runs.
🤔 Why does let give “Cannot access before initialization” instead of “not defined”?
Because the name exists (it was hoisted) but is in the temporal dead zone. “Not defined” means the name does not exist in any reachable scope.
🤔 Is it bad to use global variables?
In browser pages and test suites, yes, mostly. Globals can be changed from anywhere, which causes hard-to-find bugs and order-dependent tests. Keep variables in the smallest scope that works.
🏁 Summary
- Scope is where a name can be used: global, module, function and block scope.
let/const/classare block-scoped;varis function-scoped.- Name lookup follows the lexical scope chain from inner to outer scopes; inner names can shadow outer ones.
- Function declarations are hoisted with their body;
varis hoisted asundefined;let/const/classare in the TDZ until declared. - Keep test state in the smallest scope (inside each test or fixture) to avoid order-dependent failures.
Next, continue with Lesson 21: Closures.
🎬 Watch JavaScript and automation tutorials on YouTube!
Subscribe to SqaToolsByDY • Practice on sqatools.in