After this lesson you can look at any line of JavaScript and say which variables it can use. That skill removes a whole class of confusing "x is not defined" errors.
What scope means
Scope is the region of code where a name is available. Think of rooms in a house. A variable declared in a room can be used in that room, and in any room inside it, but not from the outside.
JavaScript has three main kinds of scope.
- Global scope: names declared outside any function or block. Available everywhere in that script.
- Function scope: names declared inside a function. Available only in that function.
- Block scope: names declared with
letorconstinside curly braces, such as anifor afor. Available only in that block.
Function scope
function makeMessage() {
const message = "hello";
return message;
}
console.log(makeMessage()); // hello
console.log(typeof message); // "undefined"message lives only inside makeMessage. Outside, the name does not exist. Using it directly (without typeof) would throw ReferenceError: message is not defined. Parameters also belong to the function's scope.
Block scope with let and const
Curly braces create a new scope for let and const:
const age = 20;
if (age >= 18) {
const label = "adult";
let note = "can vote in many places";
console.log(label, note);
}
console.log(typeof label); // "undefined"Loops work the same way. A variable declared in the for header exists only for the loop:
for (let i = 0; i < 3; i++) {
// i is available here
}
console.log(typeof i); // "undefined"var is different
Older code uses var. It ignores blocks and only respects functions:
if (true) {
var leaked = "I escape the block";
let contained = "I stay inside";
}
console.log(leaked); // I escape the block
console.log(typeof contained); // undefinedThis is why modern code prefers const and let: variables stay close to where they are used, so there are fewer surprises. The variables lesson covers the other differences.
The scope chain
When JavaScript meets a name, it looks in the current scope. If it is not there, it looks in the scope around it, then the next, until it reaches the global scope. This path is the scope chain. Inner code can read outward but never inward.
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
function show(text) {
out.textContent += text + "\n";
}
const site = "mrhimanshu.com"; // global
function outer() {
const level = "outer";
function inner() {
const own = "inner";
show(site + " / " + level + " / " + own);
}
inner();
// show(own); // would be a ReferenceError: own is not visible here
}
outer();
</script>inner can see own, level and site. outer can see level and site, but not own. Uncomment the commented line to see the error appear in the browser console.
Shadowing
If an inner scope declares a name that already exists outside, the inner one hides the outer one for that area. This is shadowing.
const name = "outer";
function test() {
const name = "inner";
console.log(name); // inner
}
test();
console.log(name); // outerThe two variables are separate. Shadowing is legal, and sometimes accidental. If you meant to change the outer variable but typed const or let again, you created a new local variable and the outer one stayed the same. Distinct, descriptive names avoid the problem.
Global variables and accidents
Variables in the global scope can be changed by any code on the page, which makes bugs hard to trace. Keep globals to a minimum. A script with many unrelated global names is asking for conflicts, especially when several scripts share a page. Modules give each file its own scope for this reason.
An older trap is assigning to a name that was never declared:
function oops() {
total = 100; // no let, const or var
}
oops();
console.log(total); // 100 in a classic script: an accidental globalIn a classic script, this creates a global variable. In strict mode and in modules, it throws a ReferenceError, which is much better. Always declare variables.
Scope and loops with callbacks
Block scope fixes a famous old bug. With var, all callbacks share one variable:
const withVar = [];
for (var i = 0; i < 3; i++) {
withVar.push(() => i);
}
console.log(withVar.map(fn => fn())); // [ 3, 3, 3 ]
const withLet = [];
for (let j = 0; j < 3; j++) {
withLet.push(() => j);
}
console.log(withLet.map(fn => fn())); // [ 0, 1, 2 ]With let, each loop pass gets its own j. Functions that remember their surrounding variables are called closures, the subject of an upcoming lesson, Closures.
Choosing the smallest scope
A useful habit is to declare each variable in the narrowest scope that works. A variable inside a loop body cannot be changed by code elsewhere, so you only need to check a few lines when something goes wrong:
function total(prices) {
let sum = 0; // needed after the loop, so it lives in the function
for (const price of prices) {
const withTax = price * 1.2; // only needed in one pass
sum += withTax;
}
return sum;
}
console.log(total([10, 20])); // 36withTax lives for a single pass, while sum has to outlive the loop. The wider a variable's scope, the more code you must read to understand how it changes.
Common mistakes
Using a variable outside its block. Declaring const result inside an if and reading it after the block gives a ReferenceError. Declare it before the block with let when you need it afterwards.
Relying on var to leak. Code that works only because var escaped a block is fragile.
Accidental globals. Forgetting const or let before an assignment. Start files with "use strict" or use modules to catch this.
Unintended shadowing. Re-declaring a name in an inner scope when you meant to reuse the outer one.
Too many globals. Wrap code in functions or modules so names do not collide.
Exercise
Predict the output before running anything, then check with the editor above. Declare const color = "red" globally. Write a function paint() that declares const color = "blue" and shows it, and another function check() that shows color without declaring it. Call both. Then add an if (true) block inside paint that declares a let shade and try to show shade after the block. Explain each result in a sentence.
Next: Hoisting.
Key points
- Scope decides where in your code a variable can be seen and used.
- Variables declared with let and const are block scoped; var is function scoped and ignores blocks.
- Inner scopes can read variables from outer scopes, but outer scopes cannot read inner ones.
- A variable with the same name as an outer one shadows it inside the inner scope.
- Assigning to an undeclared name in sloppy mode creates an accidental global; modules and strict mode throw an error instead.