Sub topic 2
Understanding Scope
This chapter assumes you can write and call functions, use if statements and for loops, and run code in a browser console or Node.js. It explains what scope is and how JavaScript finds a variable when your code uses its name. The details of how var, let, and const each behave come in later chapters.
What Scope Means
Scope is the region of your code where a variable can be used. A declaration creates a binding, which links a name to a value. That binding is visible inside its scope and invisible outside it.
Scope stops unrelated parts of a program from reading or overwriting each other's variables. A function can use a helper variable called count without breaking another count somewhere else.
JavaScript has three kinds of scope you will work with daily:
| Scope | Created by | Visible to |
|---|---|---|
| Global | The top level of a script | All code in the program |
| Function | Each function body | Code inside that function, including nested functions |
| Block | A pair of braces `{ }`, such as an `if` body or loop body | Code inside that block (for `let` and `const` only) |
Scopes Nest Inside Each Other
Scopes form a hierarchy. A block sits inside a function, and that function sits inside the global scope. Code can see variables in its own scope and in every scope that encloses it. It cannot see variables in scopes nested deeper than itself.
const appName = 'Tracker'; // global scope
function report(items) { // function scope starts here
const count = items.length;
if (count > 0) { // block scope starts here
const message = `${appName}: ${count} items`;
console.log(message); // can see message, count, and appName
}
console.log(typeof message); // 'undefined': message lived only in the block
return count;
}
console.log(report(['a', 'b'])); // logs "Tracker: 2 items", 'undefined', then 2
console.log(typeof count); // 'undefined': count lived only in the functiontypeof is used here because it returns 'undefined' for a name that cannot be found, where reading the name directly would throw an error.
How JavaScript Looks Up a Name
When code uses a variable, the engine searches for it in a fixed order:
- The current scope.
- The scope that encloses it.
- Each further enclosing scope, up to the global scope.
The search stops at the first match. If it reaches the global scope without finding the name, reading the variable throws a ReferenceError. This series of scopes is called the scope chain.
function show() {
try {
console.log(secret); // not declared anywhere
} catch (e) {
console.log(e.name); // 'ReferenceError'
}
}
show();Scope Is Lexical
JavaScript uses lexical scope. A function's enclosing scopes are set by where the function is written in the source code. Where it is called from has no effect on them.
const label = 'global';
function printLabel() {
console.log(label); // looks up label where printLabel was written
}
function caller() {
const label = 'caller';
printLabel(); // still logs 'global'
}
caller();printLabel was defined at the top level, so its scope chain goes straight to the global scope. The label inside caller is never searched.
Shadowing
An inner scope can declare a variable with the same name as an outer one. The inner binding then shadows the outer one. Inside the inner scope, the name refers to the inner variable. The outer variable is still there and keeps its value.
const level = 'global';
function outer() {
const level = 'outer'; // shadows the global level
function inner() {
console.log(level); // 'outer': nearest match wins
}
inner();
}
outer();
console.log(level); // 'global': unchangedCommon Errors
- Using a variable after its block ends. If you declare a value inside an
ifor loop body and then read it after the closing brace, you usually get aReferenceError. Declare it in the outer scope instead. - Expecting dynamic scope. A function cannot see the local variables of whoever calls it. Pass the values in as arguments.
- Accidental shadowing. A parameter or inner variable that reuses an outer name hides the outer value.
- Assuming every block creates scope. Braces create block scope only for
letandconst. Oldervardeclarations ignore blocks, which the next chapter covers.
Exercise
What does this code log, and why? const x = 1; function a() { console.log(x); } function b() { const x = 2; a(); } b();
Show answer
It logs 1. Scope is lexical: function a was written at the top level, so its lookup for x goes from a's own scope to the global scope and finds x = 1. The x declared inside b is not in a's scope chain.
Exercise
In the report example, the line console.log(message) placed after the if block would throw an error. What kind of error is it, and how would you fix it so the message is available after the block?
Show answer
It throws a ReferenceError because message is block-scoped to the if body. Declare it in the function scope before the if, for example let message = ''; and assign to it inside the block.