Skip to content

Variable Scope

A variable’s scope is the part of the program that can see it. JavaScript decides scope from where the declaration is written in the source, so reading the code tells you which variables each line can reach.

There are three main scopes:

  • Global scope: a variable declared outside every function and block can be read anywhere in the script.
  • Function scope: a variable declared inside a function exists only while that function runs, and only code inside the function can see it.
  • Block scope: a variable declared with let or const inside a pair of braces, such as an if or a loop body, exists only inside those braces.

Here shopName is global, so the function can read it, while total belongs to the function:

const shopName = 'Corner Shop';
function printReceipt() {
const total = 12.5;
console.log(`${shopName}: £${total.toFixed(2)}`);
}
printReceipt();
try {
console.log(total);
} catch (err) {
console.log(err.message);
}

This prints:

Corner Shop: £12.50
total is not defined

Reading total outside the function throws a ReferenceError, because no variable of that name exists at that point in the program.

A block is any code between braces. Variables declared in it with let or const disappear when the block ends:

const temperatures = [14, 19, 23];
for (const reading of temperatures) {
if (reading > 20) {
const note = `${reading}°C is warm`;
console.log(note);
}
}
try {
console.log(note);
} catch (err) {
console.log(err.message);
}

This prints:

23°C is warm
note is not defined

var ignores blocks and is scoped to the whole function instead, which is one reason to prefer let and const. Variable Declarations compares the three keywords.

Scopes nest. Code can read variables from its own scope and from every scope that encloses it, but not from scopes inside it. When JavaScript meets a name, it looks in the current scope first and then works outwards:

function makeGreeting(name) {
const greeting = 'Hello';
function shout() {
return `${greeting}, ${name.toUpperCase()}`;
}
return shout();
}
console.log(makeGreeting('Priya'));

This prints:

Hello, PRIYA

Because the search stops at the first match, an inner variable with the same name as an outer one hides, or shadows, the outer one. The outer variable is untouched:

const colour = 'blue';
function paintFence() {
const colour = 'green';
console.log('inside:', colour);
}
paintFence();
console.log('outside:', colour);

This prints:

inside: green
outside: blue

Assigning to a name that was never declared does not fail in sloppy mode, which is the default for a classic script. JavaScript searches outwards for the name, finds nothing, and creates a property on the global object, so the value leaks out of the function:

function countBooks() {
bookCount = 4;
}
countBooks();
console.log(bookCount);
console.log(globalThis.bookCount);

This prints:

4
4

Browsers’ classic scripts behave the same way. This is almost always a mistake, such as a forgotten let or a misspelt name. In strict mode the same assignment throws instead, which is one of the main reasons to use it:

function countPens() {
'use strict';
penCount = 4;
}
try {
countPens();
} catch (err) {
console.log(`${err.name}: ${err.message}`);
}

This prints:

ReferenceError: penCount is not defined

ES modules and class bodies are always strict, so in modern code the accidental global usually shows up as this error. Strict Mode covers the rest of what strict mode changes, and Global Variables/Properties, globalThis covers the global object.

Steve Griffith covers this topic in his video Variable Scope.