Loading

T4 JavaScript · Lesson 4

Scope

Where a name can be seen: global, function and block scope, var against let and const, the chain of scopes and shadowing, closures that remember, and why a program keeps its global names few.

  • say where a name can be seen, and read a ReferenceError about a name in another scope
  • keep names inside a function, and say what a parameter can and cannot change
  • use block scope with let and const, and spot var leaking out of a block
  • follow the chain of scopes outward, and spot a name that shadows another
  • use a closure to give a function a memory of its own
  • keep global names few, and avoid accidental globals and clashes between scripts
About 60 minutesChecked against Node.js on the laptop (the kit runs every code block with it) 22.23.1 (2026-11-06); Google Chrome on the laptop (the kit renders every HTML block in it, and the DevTools step describes its panels) 155 (2026-11-06)Play this lesson's games

The back cover

In a big program, hundreds of names live side by side: total, count, price, i. If every name could be seen and changed from everywhere, two parts of a program would trip over each other all day. Scope is the set of walls that keeps each name where it belongs.

These pages show global, function and block scope, and why let and const are safer than var. They follow the chain of scopes outward and show what shadowing does. They explain closures, functions that remember the place where they were made, and why a program keeps its global names few.

Before you start

The story: Two bells, one count

At noon the harbour bell of the Clock Tower rings fourteen times. A minute later the tram bell rings as well, though no tram has left. People in the square look up at the tower, then at their watches, then at each other.

Master Hakim Verge has the two bells' scripts side by side on his bench. They were written by different clockmakers, years apart. Each bell keeps a count of its rings, and each clockmaker called that count by the same name.

"Two hands on one winding key," says Master Verge. "Every time one bell counts, it moves the other." Corin suggests renaming one of them. Master Verge asks him how many other scripts in the tower use that name too. Corin does not know.

Every name in a program lives somewhere. Some names can be seen from anywhere in the program, and some only inside one function, or one block of an if. Where a name can be seen decides which code can read it, which code can change it, and which code can clash with it by accident. This lesson is about that question, which programmers call scope.

It builds on these ideas. Each one has a tiny example, so you can check that you remember it.

What you already knowA tiny exampleWhere it comes back
const and let.let count = 0;Both live only in their block.
var.var seats = 120;It lives in a whole function instead.
Hoisting.A var used above its line is undefined.Seen again inside a function.
The temporal dead zone.A let used above its line is an error.Seen again inside a block.
A block.Lines between { and }.Each block has a scope of its own.
if statements.if (paid) { ... }Its braces make a block.
Functions and parameters.function greet(name) { ... }Each call has its own names.
A function inside a function.return (name) => ...The inner one can see the outer one's names.
A closure.makeGreeter("Namaste")This lesson explains how it remembers.
ReferenceError.x is not definedOften means: right name, wrong scope.

By the end of this lesson you will be able to:

  • say where a name can be seen, and read a ReferenceError about a name in another scope;
  • keep names inside a function, and say what a parameter can and cannot change;
  • use block scope with let and const, and spot var leaking out of a block;
  • follow the chain of scopes outward, and spot a name that shadows another;
  • use a closure to give a function a memory of its own;
  • keep global names few, and avoid accidental globals and clashes between scripts.

How to follow this lesson

Every block on this page runs. When a name gives a surprising value, or is not defined, ask two questions: where was this name made, and where am I using it? The answer to most puzzles in this lesson is that two places were using two different names that happened to be spelt the same, or one name that should have been two.

In one line

Scope is where in a program a name can be seen, and it decides which code can read, change or clash with that name.

What scope is

At a glance

A family's address book and an office phone list may both have a Ravi, and nobody mixes them up, because each list belongs to its own place. In code, the part of a program where a name can be seen is called its scope.

A name made at the top level is global and can be seen everywhere. A name made inside a function or a block is local and can be seen only inside it. Local names let two pieces of code use the same name without a clash.

Take a guess: Can a name made inside a function be used outside it?

In a housing society, a notice on the board at the main gate can be read by everyone who lives there. A note stuck on the fridge in flat 4B can be read only by the family inside 4B. Nobody in 3A can read it, and nobody in 3A gets confused by it, even if they have a note of their own on their own fridge that says the same thing.

Names in a program work the same way. A name made at the top level of a program, outside every function and block, is like the notice at the gate. A name made inside a function is like the note on a fridge.

Scope

The part of a program in which a name can be seen and used. Outside its scope, the name does not exist.

Global scope

The scope of names made at the top level of a program, outside every function and block. A global name can be seen everywhere in the program.

Local scope

The scope of names made inside a function or a block. A local name can be seen only inside it.

const shop = "Ravi Stores";
function sign() {
  return `Welcome to ${shop}`;
}
console.log(sign());
Welcome to Ravi Stores

shop is global, so the function sign can see it, like a family reading the notice at the gate. Now the other way round. A name made inside a function cannot be seen from outside:

function f() {
  const secret = 42;
}
f();
console.log(secret);
Uncaught ReferenceError: secret is not defined
    at line 5

secret lived only inside f, and only while f was running. Outside f, there is no such name, so the last line gives the ReferenceError you know, "is not defined". This is the first meaning of that message to look for in any program with functions: the name exists, but in another scope.

Why scope is a good thing

It can seem a nuisance that a name made in one place cannot be used everywhere. In fact it is what lets large programs work at all. Consider two functions written by two people, each using a name total:

function first() {
  const total = 1;
  return total;
}
function second() {
  const total = 2;
  return total;
}
console.log(first(), second());
1 2

Each total is local to its own function, so the two never meet, and neither programmer needs to know what names the other chose. A program of a hundred thousand lines, written by fifty people over ten years, depends on this. Without local scope, every name anywhere would have to be different from every other, as the two bells of the Clock Tower found out.

Where the name is madeIts scopeWho can see it
at the top level of the programglobalevery line of the program
inside a functionthat functiononly the lines inside that function
with let or const inside a blockthat blockonly the lines inside those braces

The next three sections take these one at a time: names inside functions, names inside blocks, and what happens when scopes sit inside each other.

Worked example 1

A school's program has a global name schoolName, and a function that prints a certificate line using it and a local name for the student. Work out which lines can see which names, and print the line for Asha.

What we have: one global name, schoolName, and one local name inside the function

What we need: the certificate line, and the scope of each name

The plan: make schoolName at the top level, make the student's line inside the function, and use both inside it

const schoolName = "Vidya Niketan";
function certificate(student) {
  const line = `${student} has completed Class 9 at ${schoolName}`;
  return line;
}
console.log(certificate("Asha"));
Asha has completed Class 9 at Vidya Niketan
  1. Inside certificate, three names can be seen: student and line, which are local, and schoolName, which is global.
  2. Outside it, only schoolName and certificate itself can be seen. student and line vanish when the call ends.

It prints Asha has completed Class 9 at Vidya Niketan.

Check: the function used the global name and its own two local names, and nothing else.

A path that fails: trying to print line outside the function, to check it. That gives ReferenceError: line is not defined. Print the returned value instead, as the last line does.

When you are stuck: a name is not defined, though you can see where it was made

Find the line that made the name, and the braces around that line. The name exists only inside them.

If the name was made inside a function, return its value, and use the returned value outside.

If several functions need the same value, make it once outside them, or pass it in as an argument.

Check the spelling as well: a misspelt name gives the same message.

Your turn

const tax = 18;
function bill(amount) {
  const total = amount + amount * tax / 100;
  return total;
}
console.log(bill(100), tax);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
118 18
  1. Inside bill, the global tax is seen: 100 + 18 = 118.
  2. Outside, tax is still 18; total is not used outside.

It prints 118 18.

A program makes const price = 40; inside a function named setup, then calls setup(), then prints price on the next line. What happens?Tap to reveal
  1. price is local to setup.
  2. After the call, the name is gone, and outside setup it never existed.

ReferenceError: price is not defined.

Which of these names are global: a const made on the first line of a program, a parameter of a function, a let made inside an if block?Tap to reveal
  1. The const on the first line is at the top level: global.
  2. A parameter belongs to its function: local.
  3. A let inside an if belongs to that block: local.

Only the const on the first line.

Did you know?

Two kinds of global

Not all global names are alike. In a script, a variable declared with var at the top level is added as a property of the global object, window in a browser. A let or a const at the top level is not: MDN notes that let declarations do not create properties on globalThis. Both kinds are still global, shared by every script on the page.

Why it fits here: It refines this topic's global scope: let and const at the top level are global names, but they stay off the window object.

Sources: MDN: var; MDN: let; ECMAScript Language Specification: Global Environment Records

Global here, local there

The same line can be global in one place and local in another. In browsers, the top-level scope has traditionally been the global scope, so var something makes a new global, except within modules. Node.js's own documentation says that in Node this is different: the top-level scope is not the global scope, and var something stays local to its module.

Why it fits here: It shows that this topic's global scope depends on where the code runs: a browser script shares it, a Node module keeps its own.

Source: Node.js documentation: Global objects

In one line

A name made at the top level is global and can be seen everywhere; a name made inside a function or block is local and can be seen only inside it. Local names let two pieces of code use the same name without a clash.

Names inside a function

At a glance

Each time a recipe is cooked, the cook takes out fresh bowls; yesterday's bowls are washed and gone. A function call works the same way: it gets a fresh set of local names, its parameters included, and loses them when it returns.

So two calls of the same function never share their local names. A parameter holds a copy of a primitive value passed in. A name made with var inside a function belongs to the whole function body, not only to the lines below it.

Take a guess: If a function is called twice, do the two calls share their local names?

Every call of a function gets a fresh set of its own names, like a new page in a notebook. The page is used while the call runs, and torn out when the call returns. The parameters are written on that page too, with the values the call brought.

Function scope

The scope of names made inside a function, its parameters included. They can be seen only inside the function's body, and each call has its own set.

const greet = (name) => {
  const message = `Namaste, ${name}`;
  return message;
};
greet("Asha");
console.log(typeof message);
undefined

message existed only during the call. typeof gives undefined for a name that does not exist, instead of an error, which makes it a safe way to ask.

A parameter is a copy

When a call passes a value, the parameter gets a copy of it, as an assignment would. Changing the parameter changes only the function's own copy:

function addOne(n) {
  n = n + 1;
  return n;
}
const x = 5;
console.log(addOne(x), x);
6 5

Inside addOne, n went from 5 to 6, but x outside is still 5. The function changed its own page, not the caller's. This is true for every primitive value: numbers, strings and booleans. Objects and arrays behave differently, which the arrays and objects lessons of this track explain.

Each call starts afresh

Because each call gets a fresh set of names, a function cannot remember anything from one call to the next in its own local names. This counter never gets past 1:

function counter() {
  let n = 0;
  n++;
  return n;
}
console.log(counter(), counter(), counter());
1 1 1

Each call makes a new n, starting at 0, adds one, and returns 1. Then that n is thrown away. To remember between calls, a function needs a name that outlives the call. The closures section shows the good way to give it one.

var belongs to the whole function

A name made with var inside a function also stays inside that function:

function f() {
  var local = 1;
}
f();
console.log(typeof local);
undefined

But var differs from let and const in one way that matters: its scope is the whole function, from the top of the body, not only the block it is written in. The next section shows what that does in a block. And inside a function, var is hoisted to the top of the body, as it was hoisted to the top of the program in the values lesson:

function f() {
  console.log(v);
  var v = 5;
}
f();
undefined

Worked example 2

A delivery app works out the delivery charge for each order inside a function, from the distance in kilometres: ₹20 to start, and ₹8 for each kilometre. Show that two calls do not disturb each other, and that the distance outside stays as it was.

What we have: a global distance of 6 km, and a function with its own local names

What we need: the charge for 6 km and for 2 km, with the global distance unchanged

The plan: keep every working value local to the function, and pass the distance in as an argument

const km = 6;
function charge(distance) {
  const base = 20;
  const perKm = 8;
  distance = Math.ceil(distance);
  return base + distance * perKm;
}
console.log(charge(km), charge(2), km);
68 36 6
  1. Math.ceil rounds the parameter up to whole kilometres, and changes only the function's own copy. km outside is still 6.
  2. base and perKm are made afresh in each call, and neither is seen outside.

The charges are ₹68 and ₹36, and km is still 6.

Check: 20 + 6 × 8 = 68 and 20 + 2 × 8 = 36.

A path that fails: making base and perKm global and then changing them inside the function for a special offer. The next call, and every other function that uses them, then gets the offer too.

When you are stuck: a function seems to forget, or to change a value it should not

Each call starts with fresh local names. To remember between calls, keep the value outside the call, as the closures section shows.

A parameter is a copy of a primitive value, so changing it does not change the caller's name.

If a value outside changed, look for a line in the function that assigns to a name it did not make.

Use typeof name to ask whether a name exists where you are, without an error.

Your turn

function double(n) {
  n = n * 2;
  return n;
}
let k = 4;
const d = double(k);
console.log(k, d);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
4 8
  1. double gets a copy of 4 and doubles its copy.
  2. k outside is still 4, and d is 8.

It prints 4 8.

Why does this counter always give 1: function next() { let n = 0; n++; return n; }?Tap to reveal
  1. Each call makes a new n, starting at 0.
  2. The n from the last call was thrown away when that call returned.

Because each call starts with a fresh n.

What does typeof total give outside a function that made total with const, and why is that not an error?Tap to reveal
  1. Outside the function, total does not exist.
  2. typeof is allowed to ask about a name that does not exist, and answers undefined.

It gives undefined, with no error.

Did you know?

A fresh record for every call

Behind every call is a record the standard calls an execution context: a specification device that is used to track the runtime evaluation of code. At any moment, at most one execution context is actually running code. Each call of a function starts with a new one, so its names are its own, and they are gone when it returns.

Why it fits here: It explains this topic's fresh set of names: each call has its own record, made when it starts and dropped when it returns.

Sources: ECMAScript Language Specification: Execution Contexts; ECMAScript Language Specification: PrepareForOrdinaryCall

Known before its line

A var is known before its line runs. MDN explains that var declarations, wherever they occur in a script, are processed before any code within the script is executed, so a var anywhere acts as if declared at the top. Until its assignment is reached, the variable remains undefined. This behaviour is called hoisting.

Why it fits here: It explains why this topic says var belongs to the whole function body: the name exists from the first line, though its value comes later.

Sources: MDN: var; ECMAScript Language Specification: Variable Statement

In one line

Each call of a function gets a fresh set of local names, its parameters included, and loses them when it returns. A parameter holds a copy of a primitive value, and var inside a function belongs to the whole function body.

Names inside a block

At a glance

A hotel room's cupboard is for that room's guest; when the guest checks out, the cupboard is emptied. The next guest finds nothing of the last one's. Every pair of braces in code is like that room: a block, with its own short-lived names.

Names made with let and const inside a block live only until its closing brace, while var ignores blocks and leaks out. To use a value after a block, make its name before the block and assign it inside. A loop's let even gets a new copy each time round.

Take a guess: Can a let made inside an if block be used after the block's closing brace?

A function is not the only thing that makes a scope. Every pair of curly braces makes a block, and a block has a scope of its own for names made with let and const. The braces of an if, of an else, of a loop, or even a bare pair of braces on their own, all count.

Block scope

The scope of a name made with let or const inside a pair of braces. It can be seen only from its line to the closing brace.

if (true) {
  const inside = "here";
}
console.log(inside);
Uncaught ReferenceError: inside is not defined
    at line 4

inside was made in the if's block, so it is gone after the closing brace. This is what you want almost every time: a name made to help with one step should not hang about after that step is done.

var ignores blocks

var was made before blocks had scopes of their own, and it still ignores them. A var made inside a block belongs to the whole function around it, or to the whole program if there is no function, so it leaks out of the block:

if (true) {
  var leak = "out";
}
console.log(leak);
out

The same leak happens with the counter of a loop. Loops are the subject of a later lesson in this track; for now, look only at the last line of each block. A loop counter made with var is still there after the loop, holding its last value. One made with let is gone:

for (var i = 0; i < 3; i++) {}
console.log(i);
3
for (let j = 0; j < 3; j++) {}
console.log(typeof j);
undefined

A leaked name can collide with another name of the same spelling later in the function, or keep a value that a later line uses by mistake. This is a large part of why the values lesson advised let and const for all new code.

Made withIts scopeSeen after the block's closing brace?
constthe blockno
letthe blockno
varthe whole function, or the programyes, it leaks

A block inside a block

A block may hold another block, and a name in the inner one may use a spelling already used outside. Inside the inner block, the inner name is the one you get:

let x = 1;
{
  let x = 2;
  console.log(x);
}
console.log(x);
2
1

These are two different names that happen to be spelt the same. The inner x exists only inside the braces. Once they close, the outer x, which was never changed, is the only one left. The next section names this, shadowing, and shows when it helps and when it hurts.

The temporal dead zone of the values lesson applies inside blocks too, with a twist. Inside a block that makes its own x, the outer x cannot be used above the inner one's line, even though the outer one has a value:

let x = 1;
{
  console.log(x);
  let x = 2;
}
Uncaught ReferenceError: Cannot access 'x' before initialization
    at line 3

JavaScript decides which x a line means by the block it is in, not by which x has a value yet. Line 3 is in a block that makes its own x, so it means the inner one, which is still in its dead zone. The cure is the same as before: make names at the top of their block, before any line uses them.

Worked example 3

A cinema app checks a booking, and inside the if it works out a discount for students. A later line by another programmer prints discount for every booking. Show what happens with let, and why that is the safer outcome.

What we have: a discount made only for students, inside an if block

What we need: the discount kept inside the block, so it cannot be used by mistake for other bookings

The plan: make the discount with let inside the block, use it there, and see what the later line gets

const isStudent = true;
const price = 200;
let pay = price;
if (isStudent) {
  let discount = 40;
  pay = price - discount;
}
console.log(pay);
console.log(typeof discount);
160
undefined
  1. pay is made outside the block, so the block can change it, and the change is kept: 200 − 40 = 160.
  2. discount lived only in the block. The later line cannot pick it up by mistake.

The student pays ₹160, and discount is not visible after the block.

Check: a booking for a non-student skips the block, and pay stays 200.

A path that fails: making discount with var. It then leaks out of the block, and for a non-student booking it exists but holds undefined, so a later line such as price - discount gives NaN instead of an error.

When you are stuck: a name made inside braces is not defined after them

let and const live only in their block. If a later line needs the value, make the name before the block, and assign it inside.

If a name seems to have two values, look for a block that makes its own name with the same spelling.

If a var keeps a value it should not, change it to let, and the block will keep it inside.

Make each name at the top of its block, to stay clear of the dead zone.

Your turn

let size = "M";
if (true) {
  let size = "L";
  console.log(size);
}
console.log(size);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
L
M
  1. Inside the block, the inner size is L.
  2. After the block, only the outer size is left, and it was never changed: M.

It prints L, then M.

Change one word so that if (true) { var temp = 1; } console.log(typeof temp); prints undefined.Tap to reveal
  1. var leaks out of the block. let does not.
if (true) {
  let temp = 1;
}
console.log(typeof temp);
undefined

Change var to let.

A result must be worked out inside an if, but used after it. Where should the name be made?Tap to reveal
  1. Make it before the block, with let, so that it lives in the outer scope.
  2. Inside the block, assign to it without let.

Before the block, then assign it inside: let pay = price; if (...) { pay = ...; }.

Did you know?

A new let for every round

A loop treats let specially. MDN explains that when a for loop starts with a let declaration, a new lexical scope is created each time round, with new variables that take their values from the last iteration. The standard names the step CreatePerIterationEnvironment. Closures show it: functions made in different rounds each keep their own copy, not one shared variable.

Why it fits here: It adds a twist to this topic's block rule: a loop's braces make a fresh block, with fresh let names, on every round.

Sources: MDN: for; ECMAScript Language Specification: The for Statement

The compound statement

Braces do more than mark scope. MDN notes that the block statement is often called the compound statement in other languages: it lets you use several statements where JavaScript expects only one. That is how an if, which takes one statement, can run many lines. A block can even stand alone, braces with no if, to keep a helper name short-lived.

Why it fits here: It joins this topic to the if lessons: the braces that hold an if's lines are the same blocks that limit let and const.

Sources: MDN: Block statement; ECMAScript Language Specification: The if Statement

In one line

Every pair of braces is a block, and let and const made inside it live only until its closing brace; var ignores blocks and leaks out. To use a value after a block, make its name before the block and assign it inside.

Scopes inside scopes

At a glance

Looking for your keys, you check your pocket first, then your bag, then the room, and you stop at the first place you find them. Nobody searches the whole house while the keys are in their pocket. JavaScript looks for a name the same way.

It searches the line's own scope first, then each enclosing scope outward to the global scope, and the first match wins. An inner name with the same spelling as an outer one shadows it. That helps when it is meant, and hides a bug when it is not.

Take a guess: If a function and the global scope both have a name total, which does the function use?

Ask a child in Pune where she lives, and she may say "Kothrud", or "Pune", or "Maharashtra", or "India". Each is true, and each is inside the next. Scopes nest the same way: a block inside a function, a function inside another function, and everything inside the global scope.

When a line uses a name, JavaScript looks for it in the line's own scope first. If the name is not there, it looks in the scope around that one, then the one around that, outward, until it reaches the global scope. The first match wins. If there is no match even in the global scope, the result is a ReferenceError.

Scope chain

The path of scopes, from a line's own scope outward to the global scope, along which JavaScript looks for a name. An inner scope can see outward along its chain; an outer scope can never see inward.

const country = "India";
function outer() {
  const state = "Maharashtra";
  function inner() {
    const city = "Pune";
    return `${city}, ${state}, ${country}`;
  }
  return inner();
}
console.log(outer());
Pune, Maharashtra, India

Inside inner, city is found in inner's own scope. state is not there, so JavaScript looks one step out, in outer, and finds it. country is in neither, so it looks one more step out, in the global scope. The chain is decided by where the code is written, not by where it is called from. This is called lexical scope, from the Greek for "word": the written words of the program decide it.

Shadowing

When an inner scope makes a name with a spelling that an outer scope already uses, the inner name hides the outer one from every line inside the inner scope. This is called shadowing: the inner name stands in front of the outer one, like a shadow.

const city = "Pune";
function show() {
  const city = "Delhi";
  return city;
}
console.log(show(), city);
Delhi Pune

Inside show, the search for city stops at show's own city, Delhi. The global city is never reached, and never changed. Outside, only the global one exists.

Shadowing can be useful. A function can use a short, natural name such as total or rate without worrying about a name somewhere outside. But it can also hide a mistake, when the inner name was meant to be the outer one:

let total = 0;
function addItem(price) {
  let total = 0;
  total += price;
  return total;
}
addItem(50);
addItem(20);
console.log(total);
0

The programmer meant addItem to add to the global total, but the let inside made a new local total that shadows it. Each call adds to its own local total, which is then thrown away, and the global stays 0. Remove the inner let, and the line total += price; reaches the global total along the chain.

The same search explains the function that reads a nearby level of the chain rather than the global one:

let level = "global";
function a() {
  let level = "a";
  function b() {
    return level;
  }
  return b();
}
console.log(a(), level);
a global

b has no level of its own. One step out is a's level, so the search stops there, and the global level is never reached.

A common mistake

Shadowing a name by accident, then wondering why a change does not show. When a value "will not change", look for a let, const or parameter of the same spelling in an inner scope. A code checker called a linter can be set to warn about every shadowed name.

Worked example 4

A shop's program has a global GST rate of 18%. One function works out the price of medicines, which here are taxed at 5%. Show how a local rate shadows the global one inside that function only.

What we have: a global rate of 18, and a function that needs a rate of 5

What we need: the medicine price at 5%, with the global rate still 18 for everything else

The plan: make a local rate inside the medicine function; it shadows the global rate there and nowhere else

const rate = 18;
function medicinePrice(amount) {
  const rate = 5;
  return amount + amount * rate / 100;
}
function clothesPrice(amount) {
  return amount + amount * rate / 100;
}
console.log(medicinePrice(200), clothesPrice(200), rate);
210 236 18
  1. Inside medicinePrice, rate is the local 5. Inside clothesPrice there is no local rate, so the chain reaches the global 18.

The medicine costs ₹210, the clothes ₹236, and the global rate is still 18.

Check: 200 + 5% of 200 = 210; 200 + 18% of 200 = 236.

Another way: give the local name its own spelling, such as medicineRate. Nothing is shadowed, and a reader never has to work out which rate a line means.

When you are stuck: a name has a value you did not expect

Walk the chain from the line outward: its own block, the function, any outer function, then the global scope. The first match is the one used.

Look for a let, const or parameter in an inner scope with the same spelling: it shadows the outer name.

Remember that the chain follows where the code is written, not where it is called from.

If the search finds nothing at all, the result is "is not defined".

Your turn

const name = "outer";
function speak() {
  const name = "inner";
  return () => name;
}
console.log(speak()(), name);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
inner outer
  1. The arrow is written inside speak, so its chain passes through speak first.
  2. speak's name is inner, and it shadows the global one there.
  3. Outside, name is still outer.

It prints inner outer.

Inside a function, total += price; should add to a global total, but the global stays 0. What is the most likely cause?Tap to reveal
  1. The line reached a total before it reached the global one.
  2. So there is a total made inside the function, or a parameter named total, which shadows the global.

A local total shadows the global one; remove the inner declaration.

Can an outer function see a name made inside a function that is written inside it?Tap to reveal
  1. The chain goes outward only.
  2. The outer function's lines look in their own scope, then further out, never inward.

No: an outer scope never sees inward.

Did you know?

The statement that bent the chain

One old statement made the chain hard to follow. The with statement extends the scope chain for a statement, so a plain name inside it could mean a property of an object or a variable, depending on the object. MDN says its use is not recommended, as it may be the source of confusing bugs and makes optimization impossible, and it is forbidden in strict mode.

Why it fits here: It shows why this topic's lookup rule matters: when the chain is fixed by where code is written, a name can be found by reading.

Sources: MDN: with; ECMAScript Language Specification: The with Statement

Scope by the shape of the code

Finding names by where code is written is called lexical scope, and it was once a new idea. The original Lisp interpreter of 1960 used dynamic scope, which looks a name up by the calls running at the time. Scheme, from Guy Steele and Gerald Sussman at the MIT AI Laboratory, was the first dialect of Lisp to choose lexical scope.

Why it fits here: It names the rule of this topic: the chain of scopes follows the shape of the code as written, not the order of the calls.

Sources: Wikipedia: Scope (computer science); Wikipedia: Scheme (programming language); Scheme research: The Lambda Papers

In one line

JavaScript looks for a name in the line's own scope, then outward step by step to the global scope, and the first match wins. An inner name with the same spelling shadows the outer one, which helps when meant and hides bugs when not.

Closures: functions that remember

At a glance

A schoolbag carries the things packed at home, wherever the child goes. The child can open the bag at school, long after leaving home. A function made inside another function carries something similar: the names of the place where it was made.

Such a function is a closure, and it sees those names' latest values, even after the outer function has returned. Each call of the outer function makes a separate closure. That is how a function gets a private memory, such as its own count.

Take a guess: Can a closure still read a name after the function that made it has returned?

The counter in the functions section forgot everything between calls, because each call made a fresh count. Yet the makeGreeter of the functions lesson remembered its greeting long after makeGreeter had returned. The difference is where the remembered name lives.

A function made inside another function can see the outer function's names, along the chain. If the inner function is returned, or kept somewhere, it carries that view with it. The outer function's names stay alive for as long as the inner function can still use them.

Closure

A function together with the names it can see from the scope where it was made. The function keeps those names alive, and can read and change them, even after the outer function has returned.

function makeCounter() {
  let count = 0;
  return () => {
    count++;
    return count;
  };
}
const a = makeCounter();
const b = makeCounter();
console.log(a(), a(), b(), a());
1 2 1 3

Follow it slowly. Each call of makeCounter makes a fresh count, starting at 0, and returns an arrow that can see that count. The name a holds the arrow from the first call, with its own count. The name b holds the arrow from the second call, with a different count. Calling a twice gives 1, then 2. Calling b gives 1, as its count is its own. Calling a again gives 3.

This is exactly what the two bells of the Clock Tower needed: each bell's count, kept where only that bell's script can reach it. No other code can read or change a's count, because no other code was written inside that call of makeCounter. The count is private to a.

A closure sees the name, not a copy

A closure does not take a photograph of the values at the moment it is made. It keeps the names themselves, so it always sees their latest values:

let msg = "hi";
const say = () => msg;
msg = "bye";
console.log(say());
bye

say was made while msg held hi, but by the time it runs, msg holds bye, and that is what it sees. Usually this is what you want. When it is not, copy the value into a const inside the function that makes the closure, so that nothing else can change it.

Private state

Closures are a common way to keep a value that only certain functions may change. This wallet starts with a balance, and the only way to change the balance is through the function that makeWallet returns:

function makeWallet(start) {
  let balance = start;
  return (amount) => {
    balance = balance + amount;
    return balance;
  };
}
const wallet = makeWallet(500);
console.log(wallet(-120), wallet(-80), wallet(200));
380 300 500

Spend 120, then 80, then add 200: the balance goes 380, 300, 500. No line outside can set balance to a million, because no line outside can see it. The objects lesson of this track shows how to return several such functions together, for example one to spend and one to read the balance.

Functions made to order

A closure can also fix a setting once, and make a family of small functions from one maker:

function makeAdder(n) {
  return (x) => x + n;
}
const add5 = makeAdder(5);
const add10 = makeAdder(10);
console.log(add5(1), add10(1), add5(add10(0)));
6 11 15

add5 remembers an n of 5, and add10 an n of 10. The last call feeds one into the other: add10(0) is 10, and add5(10) is 15.

Worked example 5

A railway's booking counter gives each passenger a booking number that goes up by one for every booking: 101, 102, 103 and so on. Two counters, at two stations, must keep separate numbers. Write a maker for such counters, and book two passengers at the first station and one at the second.

What we have: a starting number for each station, and bookings at two stations

What we need: numbers that go up by one, separately at each station

The plan: make each station's next number a private name inside a maker, and return an arrow that gives the next number

function makeBooker(first) {
  let next = first;
  return () => {
    const number = next;
    next++;
    return number;
  };
}
const pune = makeBooker(101);
const nagpur = makeBooker(501);
console.log(pune(), pune(), nagpur());
101 102 501
  1. Each booker keeps its own next. pune's goes 101, then 102; nagpur's starts at 501, untouched by pune's bookings.

Pune gives 101 and 102, and Nagpur gives 501.

Check: a third Pune booking would give 103, and Nagpur's next would be 502.

A path that fails: keeping one global next for both stations. The two counters then share one number, as the two bells shared one count, and Nagpur's first passenger gets 103.

When you are stuck: a closure gives a value you did not expect

Remember that a closure sees the names themselves, so it sees their latest values, not the values when it was made.

Each call of the maker gives a separate closure with separate names. Two functions from two calls never share them.

If a value should be shared, make it outside the maker; if it should be private, make it inside.

Print the private value from inside the returned function, as no code outside can see it.

Your turn

function makeCounter() {
  let count = 10;
  return () => {
    count--;
    return count;
  };
}
const down = makeCounter();
console.log(down(), down(), makeCounter()());
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
9 8 9
  1. down has its own count, starting at 10: 9, then 8.
  2. makeCounter()() makes a brand-new closure and calls it once: 9.

It prints 9 8 9.

Why can no code outside makeWallet change balance directly?Tap to reveal
  1. balance is made inside makeWallet, so it is local to that call.
  2. Only the arrow written inside that call can see it, along its chain.

Because balance is in a scope that only the returned function can see.

Write makeMultiplier(n) that returns a function multiplying its argument by n, and use it to make triple.Tap to reveal
function makeMultiplier(n) {
  return (x) => x * n;
}
const triple = makeMultiplier(3);
console.log(triple(7));
21

triple(7) gives 21.

Did you know?

Scheme-ish functions

JavaScript's closures come from a deliberate choice. Brendan Eich has written that he was recruited to Netscape with the promise of doing Scheme in the browser. Looking back in 2008, he wrote that he was happy he chose Scheme-ish first-class functions and Self-ish prototypes as the main ingredients. First-class functions with lexical scope are what make closures.

Why it fits here: It shows that this topic's closures are no accident of JavaScript: they came with the Scheme-style functions it was built on.

Source: Brendan Eich: Popularity

Private before the hash

For years, closures were JavaScript's way to keep a value private. MDN explains that JavaScript, prior to classes, didn't have a native way of declaring private methods, and that closures could emulate them. ECMAScript 2022 gave classes a # prefix for private elements, and MDN notes that closures can emulate it, but cannot compare to the # syntax in ergonomics.

Why it fits here: It shows what this topic's private memory is for: a count that no code outside the closure can change.

Sources: MDN: Closures; MDN: Private elements; ECMAScript 2022 Language Specification

In one line

A closure is a function that keeps the names of the scope where it was made, and sees their latest values. Each call of a maker gives a separate closure, which is how a function gets a private memory, such as its own count.

Keeping global names few

At a glance

A notice board in a housing society can be read and changed by everyone, which is useful for notices and dangerous for anything private. One careless note can cover another. Global names are that board.

Any code can read or change a global name, so keep global names few. Declare every name, because an undeclared assignment quietly makes a global, which strict mode stops. All the scripts of one page share one global scope, so their global names can collide.

Take a guess: What happens when two scripts on one page both make a global named total?

The notice board at a society's gate is useful, but if every family pinned every note there, nobody could find anything, and two families would soon pin notes that contradict each other. Global names are the same. A few are useful; many cause trouble.

Any function can read a global name, and any function can change one, if it was made with let or var:

let count = 0;
function add() {
  count++;
}
add();
add();
console.log(count);
2

That is convenient for a small program, and dangerous in a large one. When count has a wrong value, every function in the program is a suspect, because every function could have changed it. A value kept inside a function, or in a closure, has only a few suspects.

Globals made by accident

A name used in an assignment without let, const or var is not an error in an ordinary script. JavaScript quietly makes a new global name instead:

function f() {
  total = 10;
}
f();
console.log(total);
10

total was never declared, yet after the call it exists everywhere. A misspelt name in an assignment, such as totl = 10 for total, does the same: it makes a second, global name, and the real total is left unchanged. Strict mode, which the modern JavaScript step explains, turns this into an error. It is switched on by the line "use strict"; at the top of a program:

"use strict";
function f() {
  total = 10;
}
f();
console.log(total);
Uncaught ReferenceError: total is not defined
    at f (line 3)
    at line 5

Modules and classes, which the modern JavaScript step teaches, are always in strict mode, so code written in them gets this protection without asking. Until then, declare every name with let or const, and an accidental global can never be made.

One page, many scripts, one global scope

A web page often loads several scripts: the page's own, a chat widget's, an analytics script's. In a browser, all ordinary scripts on one page share one global scope. A global name in one script is a global name in all of them, and two scripts that choose the same global name collide. This block has three scripts. The second makes a name that the first already made:

<!DOCTYPE html>
<title>Two scripts</title>
<script>
  let count = 0;
  var shopName = "Ravi Stores";
</script>
<script>
  let count = 5;
</script>
<script>
  console.log(`${count} ${window.shopName} ${window.count}`);
</script>

The Console shows

Info     0 Ravi Stores undefined
Error    Uncaught SyntaxError: Identifier 'count' has already been declared

The kit served this page from a small real server and read Chrome's Console, as the notes under the block show. The second script fails with a SyntaxError, because count is already a global name, made by the first script. The whole of the second script is refused, so its count of 5 never exists. The third script runs, and sees the first script's count, 0. In a real page, the second script might be a widget written by another company, which then stops working on your page, and the only clue is the red line in the Console of the DevTools step.

The last two values show one more difference between var and let. A var made at the top level of a script becomes a property of the browser's global object, window, so window.shopName is Ravi Stores. A let or const at the top level does not, so window.count is undefined. In any JavaScript program, browser or Node, the global object can also be reached as globalThis.

How old code kept names out of the global scope

Before let, const and modules, programmers wrapped a whole script in a function and called it at once, so that its var names became local to that function. You will meet this shape in older code. It is called an immediately invoked function expression, or IIFE, read "iffy":

(function () {
  var hidden = "inside";
  console.log(hidden);
})();
console.log(typeof hidden);
inside
undefined

The function is written in round brackets, and the second pair of brackets calls it on the spot. hidden is local to it, so the global scope stays clean. Today, block scope and modules do the same job more plainly, but the IIFE still appears in old scripts and in the output of some tools.

HabitWhy
declare every name with const or letno accidental globals
keep working values inside functions and blocksfewer suspects when a value is wrong
pass values in as arguments, and return resultseach function shows what it needs and gives
use a closure for a value that must last between callsthe value is private to the functions that need it
keep the few real globals as const, in capitalsthey are settings, and nothing can change them by mistake

Worked example 6

A page loads two scripts written by two teams. Both keep a count of clicks in a global let named count, so the second script fails with a SyntaxError. Rewrite each team's count so that the two can never collide, and show both counts working.

What we have: two teams, each needing a click counter, and one shared global scope

What we need: two counters that cannot collide

The plan: give each team a counter made by a closure, so that each count is private; only the two counter functions need names

function makeCounter() {
  let count = 0;
  return () => {
    count++;
    return count;
  };
}
const menuClicks = makeCounter();
const chatClicks = makeCounter();
menuClicks();
menuClicks();
chatClicks();
console.log(menuClicks(), chatClicks());
3 2
  1. Neither count is a global name, so neither can collide with anything. Each team's code only needs its own counter function.

The menu has been clicked 3 times and the chat 2 times, with no shared name.

Check: menu: three calls give 3; chat: two calls give 2.

A path that fails: renaming one count to count2. It works until a third script also chooses count2. A name kept out of the global scope cannot collide at all.

When you are stuck: a global name has a wrong value, or a script fails with a name already declared

Search the whole program, and every script on the page, for the name. Any function or script may have changed or made it.

For an accidental global, look for an assignment to a name with no let, const or var; "use strict"; turns it into an error that names the line.

For a clash between scripts, move each script's names into a function, a closure or a module.

In the browser, the Console of the DevTools step shows the SyntaxError of a refused script, with its file.

Your turn

let score = 10;
function bonus() {
  score = score + 5;
}
bonus();
bonus();
console.log(score);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
20
  1. bonus has no score of its own, so it changes the global score along the chain.
  2. Two calls add 5 twice: 10 + 5 + 5 = 20.

It prints 20.

A function contains the line totl = total + 1;, with total spelt wrongly on the left. In an ordinary script, what happens, and what would strict mode do?Tap to reveal
  1. In an ordinary script, totl becomes a new global name, and total is never changed: no error at all.
  2. In strict mode, the assignment to an undeclared name is a ReferenceError that names the line.

A silent new global; strict mode gives ReferenceError: totl is not defined.

Two scripts on one page both make let theme = "dark"; at the top level. Which one fails, and with what?Tap to reveal
  1. Both scripts share the page's global scope.
  2. The first runs; the second makes a name that already exists.
  3. So the second is refused with a SyntaxError: Identifier 'theme' has already been declared.

The second script fails, with a SyntaxError.

Did you know?

The name that broke websites

Even the name for the global object was hard to choose. A proposal for one name that works in every environment first tried the name global, but shipping it broke some existing websites, which already used that name for their own purposes. After gathering data on a short list of choices, the proposal settled on globalThis, a name highly likely to be web compatible.

Why it fits here: It is this topic's danger at the scale of the web: global names already in use can block even the language's own new names.

Source: TC39: proposal-global

Modules are strict from the start

A misspelt name in an assignment is a classic way to make a global by accident. MDN explains that in sloppy mode, mistyping a variable in an assignment creates a new property on the global object and the code goes on as if it worked. Strict mode turns that into an error. In a module it needs no switch: module code is always strict mode code.

Why it fits here: It shows the safest home for this topic's rule: in a module, an undeclared assignment fails at once instead of quietly making a global.

Sources: MDN: Strict mode; ECMAScript Language Specification: Strict Mode Code

In one line

Any code can read or change a global name, so keep global names few. Declare every name, as an undeclared assignment makes a global (strict mode stops it). All the scripts of one page share one global scope, so their global names can collide.

Where it is used

Scope decides how safely the pieces of a program can share a page, a server or a team. Here is where each idea of this lesson shows up in real work.

What you learnedWhere it is usedA real example
local names in functionsevery function of every programtwo programmers each use a name total in their own functions, and nothing clashes
block scope with let and constworking values inside if and loop blocksa discount worked out inside an if, and gone after it
the scope chaininner functions using outer settingsa function inside a form handler reads the form's settings from the function around it
shadowingshort local names, and a common buga local total that hides the global one, so the global never changes
closuresprivate state, counters and factoriesa booking counter per station; a function made to order, such as add5
few globalspages that load many scriptsa chat widget's script and a shop's script on one page, each keeping its names to itself
strict modemodules, classes and careful scriptsa misspelt assignment caught as an error, not made into a global
the IIFEolder scripts and the output of some toolsa whole script wrapped in a function that is called at once

Mistakes and debugging

These are the slips that people meet most often with scope. Every output below is the real one, from the code shown.

1. Using a name outside the function that made it

function f() {
  const secret = 42;
}
f();
console.log(secret);
Uncaught ReferenceError: secret is not defined
    at line 5

The fix: return the value from the function, and use what it returns.

2. Using a name after the block that made it

if (true) {
  const inside = "here";
}
console.log(inside);
Uncaught ReferenceError: inside is not defined
    at line 4

The fix: make the name before the block with let, and assign it inside.

3. A var that leaks out of a block

if (true) {
  var leak = "out";
}
console.log(leak);
out

No error: var ignores blocks. The fix: use let or const.

4. A local name that shadows the one you meant

let total = 0;
function addItem(price) {
  let total = 0;
  total += price;
  return total;
}
addItem(50);
console.log(total);
0

No error: the function changed its own total. The fix: remove the inner let, or better, return the new total and assign it outside.

5. An accidental global

function f() {
  total = 10;
}
f();
console.log(total);
10

No error in an ordinary script. The fix: declare every name; with "use strict"; at the top, the same line is a ReferenceError.

6. A name used above its own line in a block that shadows it

let x = 1;
{
  console.log(x);
  let x = 2;
}
Uncaught ReferenceError: Cannot access 'x' before initialization
    at line 3

The fix: make names at the top of their block, or give the inner one a different spelling.

7. A function that forgets between calls

function counter() {
  let n = 0;
  n++;
  return n;
}
console.log(counter(), counter());
1 1

No error: each call makes a fresh n. The fix: keep the count in a closure, made once by a maker function.

The debugging corner: find where the name was made

For any scope puzzle, find the line that made the name, then the braces around that line. Those braces are the name's whole world. Then walk outward from the line that uses it, block by block, until you meet a declaration of that spelling: that is the name the line really uses. In the Sources panel of the DevTools step, the Scope pane lists the names of each level of the chain while the code is paused, with Local at the top and Global at the bottom.

Quick card

The whole lesson on one card. Come back to it whenever you need a reminder.

The lesson in code

// global: seen everywhere; local: seen only inside its function or block
const SHOP = "Ravi Stores";
function sign(name) {
  const line = `${name} at ${SHOP}`;
  return line;
}
console.log(sign("Asha"), typeof line);

// let and const live in their block; var leaks out
if (true) {
  let a = 1;
  var b = 2;
}
console.log(typeof a, b);

// the chain looks outward; an inner name shadows an outer one
const rate = 18;
function medicine(amount) {
  const rate = 5;
  return amount + amount * rate / 100;
}
console.log(medicine(200), rate);

// a closure keeps its own private names alive between calls
function makeCounter() {
  let count = 0;
  return () => ++count;
}
const clicks = makeCounter();
clicks();
console.log(clicks());
Asha at Ravi Stores undefined
undefined 2
210 18
2
When you seeIt meansLook at
ReferenceError: x is not definedthe name is in another scope, or misspeltthe braces around the line that made it
ReferenceError: Cannot access 'x' before initializationthe name is used above its line in its own blockdeclarations at the top of each block
a value that will not changea local name shadows the one you meantinner let, const and parameters of that spelling
a name that exists where it should nota var that leaked, or an accidental globalvar, and assignments with no declaration
SyntaxError: Identifier '...' has already been declared in a second scripttwo scripts on one page chose the same global namemove each script's names into a function or closure
a counter stuck at 1a fresh local name on every calla closure made once

The story: Each bell its own count

You give each bell's count a home inside its own script, where no other script can reach it. Each script still sees everything it needs from the tower, but nothing outside can touch its count, and its count touches nothing outside.

At one o'clock the harbour bell rings once. The tram bell waits, and rings only when the 1.05 pulls out of the square.

Master Verge listens to the single stroke and nods. "A name should live only where it is needed," he says. "Then two clockmakers who never meet can still share a tower."

Reagents gathered: scope, block, global, shadowing, closure.

Sources