Scope and hoisting
Overview
Scope decides where a variable can be used. JavaScript has these levels:
- Global scope — declared outside any function or block; visible everywhere.
- Module scope — in a JavaScript module, top-level variables are visible in that file only.
- Function scope — declared inside a function; visible only in that function.
- Block scope —
letandconstinside{ }are visible only in that block.
const site = 'Academy'; // global
function showLesson() {
const lesson = 'Scope'; // function scope
if (true) {
const note = 'block only'; // block scope
console.log(site, lesson, note);
}
// console.log(note); → ReferenceError
}Scopes keep variables from different parts of a program from interfering with each other. Two functions can both have a variable called total, and they’ll never clash.
The scope chain
Scopes nest inside each other like boxes. When you use a name, JavaScript looks in the current scope first, then the one around it, and so on out to the global scope. Inner code can see outer variables — never the reverse.
If the name isn’t found anywhere — even in the global scope — you get a ReferenceError: x is not defined.
function outer() {
const a = 1;
function inner() {
const b = 2;
console.log(a + b); // 3 — inner can see a
}
inner();
console.log(b); // ReferenceError — outer can't see b
}Lexical scope
Scope is decided by where code is written, not where it’s called from. A function always sees the variables around its definition:
const label = 'global';
function show() {
console.log(label);
}
function run() {
const label = 'local to run';
show(); // 'global' — show was written outside run
}
run();This rule (“lexical” scope) is what makes closures work, as you’ll see in the Closures topic.
Shadowing
Declaring a variable with the same name in an inner scope hides (shadows) the outer one. Inside the inner scope, the name refers to the new variable; the outer one is untouched:
const colour = 'blue';
function paint() {
const colour = 'red'; // shadows the outer colour
console.log(colour); // 'red'
}
paint();
console.log(colour); // 'blue'Shadowing is legal, but it’s often accidental, as in this topic’s exercise: writing let status = … inside the function creates a brand-new variable instead of updating the outer one. Linters such as ESLint can warn you about it.
Global variables
Variables in the global scope are visible to every script on the page. That makes them convenient — and risky:
- Any code can change them, so bugs are hard to trace.
- Two scripts can accidentally use the same name and overwrite each other.
Keep the global scope as empty as possible. Wrap code in functions, or use JavaScript modules (covered in Modules), where top-level variables are private to the file automatically.
In browsers, top-level var declarations and function declarations in classic scripts also become properties of the global window object. let and const don’t — another small reason to prefer them.
Hoisting
Before running a scope, JavaScript first scans it and registers every declaration in it. That’s called hoisting (as if declarations were “lifted” to the top), and it behaves differently per keyword:
sayHi(); // works: function declarations are hoisted whole
function sayHi() { console.log('Hi'); }
console.log(a); // undefined: var is hoisted, but not its value
var a = 1;
console.log(b); // ReferenceError: b is in the "temporal dead zone"
let b = 2;| Declaration | Hoisted? | Value before its line |
|---|---|---|
function f() {} |
Yes, completely | The function — you can call it |
var x |
Yes | undefined |
let x / const x |
Yes, but uninitialised | ReferenceError (temporal dead zone) |
class C {} |
Yes, but uninitialised | ReferenceError |
const f = () => {} |
Like const |
ReferenceError |
The temporal dead zone
let and const are hoisted — the engine knows the name exists from the start of the block — but they can’t be used until their declaration line runs. The gap between the start of the block and that line is the temporal dead zone (TDZ). This explains a surprising error:
const name = 'outer';
function show() {
console.log(name); // ReferenceError, not 'outer'!
const name = 'inner';
}Because the inner name is hoisted to the top of show, it shadows the outer one for the whole function — but it’s still in the dead zone on the console.log line.
In practice: declare variables at the top of the block that uses them, and you’ll never notice hoisting.
Loops and block scope
Each iteration of a for loop with let gets its own copy of the loop variable. That matters when functions created in the loop use it later:
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100); // 0, 1, 2
}
for (var j = 0; j < 3; j++) {
setTimeout(() => console.log(j), 100); // 3, 3, 3 — one shared variable
}With var there’s just one j for the whole function, and by the time the timers run it has reached 3.
Fix the scope bug
This logs undefined. Change one line so it prints 'ready'.
let status;
function setup() {
let status = 'ready';
}
setup();
console.log(status);let status;
function setup() {
status = 'ready'; // update the outer variable instead of declaring a new one
}
setup();
console.log(status);Summary
- Scope is where a variable is visible: global, module, function or block.
- Inner code can read outer variables, but not the other way round — lookups go outwards.
- Declaring the same name in an inner scope shadows the outer variable.
let/constexist from their line onwards;varis hoisted asundefined; function declarations are hoisted whole.- Scope is decided by where code is written, not where it’s called (lexical scope).