Skip to content
FunctionsChapter 15 / 47Intermediate5 min read

Scope & Hoisting

Understand JavaScript scope and hoisting, global, function and block scope, the difference between var, let and const, and the Temporal Dead Zone.

On this page

1. What are scope and hoisting?

Before running code, JavaScript scans every scope and remembers the variables and functions declared in it. This is called hoisting. The code is not physically moved up, the engine just knows in advance which name belongs to which scope.

2. Why does it matter?

If you do not understand scope, variables overwrite each other and you get strange undefined values or ReferenceError.

Old var codeModern let and const
var leaks outside the blocklet and const stay in their own block
Using before declaring gives undefinedUsing before declaring gives a clear error
Loop callbacks all see the last valueEach iteration has its own value
The same name can be declared againA duplicate declaration is an error

3. Where is it used?

SituationThe role of scope
Loopslet i creates a new binding for each iteration
ModulesEach file has its own module scope, so globals are not polluted
FunctionsInner variables stay private from the outside
ClosuresAn inner function remembers the variables of the outer scope
DebuggingUnderstanding ReferenceError and TDZ errors

4. How does it work?

Levels of scope

ScopeWho creates itWhat it holds
GlobalThe top level of a file (script)Accessible from everywhere
ModuleA file with import / exportOnly inside that file
FunctionEvery functionvar, let, const, all of them
Block{ }, if, forOnly let, const, class

When a variable is looked up, the engine moves from the inside outward. This is called the scope chain. JavaScript uses lexical scope, which means scope is decided by where the code was written, not where it was called.

Variable lookup (scope chain)
Current block scope
The outer function scope
Module or global scope
If not found, ReferenceError

How hoisting behaves

DeclarationIs it hoisted?Access before the declaration
function foo()Yes, the whole functionWorks
var xYes, with the value undefinedYou get undefined
let / constYes, but uninitializedReferenceError (TDZ)
classYes, but uninitializedReferenceError (TDZ)
const fn = () => {}The const ruleReferenceError (TDZ)

The Temporal Dead Zone (TDZ) is the part from the start of the block up to the declaration line. During this time, touching a let or const variable throws an error.

5. Code example

See hoisting

js
console.log(sayHi());
console.log(count);

function sayHi() {
  return "Hi";
}

var count = 5;

try {
  console.log(total);
} catch (error) {
  console.log(error.name);
}

let total = 10;

Block scope and loops

js
for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log("var:", i), 0);
}

for (let j = 0; j < 3; j++) {
  setTimeout(() => console.log("let:", j), 0);
}

if (true) {
  const secret = "block only";
}
console.log(typeof secret);

How does the code work?

ItemMeaning
sayHi() called firstA function declaration is fully hoisted, Hi is printed
count logged firstvar is hoisted but its value is undefined
total accessed firstIt is in the TDZ, ReferenceError is printed
var i loopOne i is shared, 3 is printed three times
let j loopA new j for each iteration, 0 1 2 is printed
typeof secretNot visible outside the block, undefined

Interview tip

The right answer to "Is let hoisted?" is: yes, but it is not initialized, so accessing it in the TDZ throws a ReferenceError. var is hoisted and initialized with undefined.

6. Common mistakes

Mistake: Using var in new code

Why? var is function scoped, leaks out of blocks and gives the wrong value in loop callbacks.

Better: Keep const as the default, use let if the value must change. Learn var only to understand old code.

Mistake: Calling a function expression before its declaration

Why? const handler = () => ... is in the TDZ, so calling it before the declaration line throws a ReferenceError.

Better: Define expressions first, then use them. Or write a function declaration if you need to call it above.

Mistake: A variable with the same name inside and outside

Why? The inner variable shadows the outer one, and you think you changed the outer one but you did not.

Better: Use separate, clear names and turn on the linter's no-shadow rule.

7. What to learn before and after

Suggested order
Variables
Functions
Scope & Hoisting
Closures

Final quick revision

PointDetail
ScopeWhere a variable is accessible from
Lexical scopeScope is decided by where the code was written
Block scopelet, const, class
varFunction scoped, hoisted as undefined
TDZAccessing let / const before the declaration line is an error
Function declarationFully hoisted, can be called from above