Scope and the Lexical Environment
Scope determines where a variable can be accessed. JavaScript uses lexical scoping, meaning scope is decided by where code is written, not where it runs.
A lexical environment is local memory plus a reference to the parent environment. The scope chain walks up through parents until it finds the variable or reaches global scope.
EXERCISE
1What Is Scope?
Scope answers one question: where can I use this variable? Understanding scope is the key to understanding why some variables are accessible and others are not.
Scope is the set of places in your code where a given name can be read. It is fixed by where you write the code, not by what happens while it runs, which is why you can work it out by reading rather than by testing. A name declared inside a function is visible inside that function and inside anything nested within it. From outside, that name does not exist.
The relationship only runs one way, and that asymmetry is the whole of this lesson.
A function can read names from outside itself:
const language = "JavaScript";
function printLanguage() {
console.log(language); // "JavaScript"
}
printLanguage();
printLanguage has no language of its own. When the lookup fails inside the function, continues outward and finds the one declared at the top level. Nothing special is happening here; this is ordinary and you rely on it constantly without thinking about it.
The reverse fails:
function secret() {
const password = "abc123";
console.log(password); // "abc123"
}
secret();
console.log(password); // ReferenceError: password is not defined
password exists only while secret is running, and only inside it. Once the function returns, the name is gone. From the outside it was never visible at any point, which is what makes function internals genuinely private rather than private by convention.
Nesting extends the same rule rather than adding a new one:
function outer() {
const message = "Hello";
function inner() {
console.log(message); // "Hello"
}
inner();
}
outer();
inner can read message because inner is written inside outer. It would still be able to if it were nested three levels deep. What it could never do is work the other way round: outer cannot see anything declared inside inner.
That one-way flow is worth stating as a rule you can apply without thinking: a function can always read outward, and never inward. Everything else in this unit follows from it.
The same rule applies to blocks, not just functions, once you are using let and const:
if (true) {
const temporary = "gone soon";
console.log(temporary); // "gone soon"
}
console.log(temporary); // ReferenceError: temporary is not defined
Nothing new is happening here. A block creates a scope, the name lives inside it, and reading it from outside fails exactly as it did with the function. Scope is one idea applied consistently, which is what makes it possible to reason about without memorising cases.
EXERCISE
2The Lexical Environment and Scope Chain
Every time an execution context is created, a lexical environment is also created. It is the combination of local memory plus a reference to the parent lexical environment.
"Lexical" means determined by position in the source text. A function's scope is fixed by where you wrote it, and nothing that happens at runtime can change it. You can pass a function somewhere else entirely, call it from another file, store it in an object, and it will still look for names in the place it was written, not the place it was called.
This is worth being precise about because the alternative exists in other languages. Under dynamic scoping a function would resolve names from wherever it was called. JavaScript does not do that, and the consequence is that scope is a reading exercise rather than a exercise.
The lookup walks outward through the places the code is written:
const name = "Global";
function parent() {
const name = "Parent";
function child() {
console.log(name); // "Parent"
}
child();
}
parent();
child checks its own scope first and finds nothing. It then checks parent, the function it is written inside, and finds name there. It stops immediately. The global name is never consulted, because the search ends at the first match.
The chain can be any depth, and works the same way at every level:
const color = "red";
function first() {
function second() {
function third() {
console.log(color); // "red"
}
third();
}
second();
}
first();
Three functions deep, and none of them declares color. The lookup goes through third, second, first and finally the top level, where it succeeds.
When the chain runs out, you get an error rather than a default:
function search() {
function deeper() {
console.log(missing); // ReferenceError: missing is not defined
}
deeper();
}
search();
There is no scope beyond the outermost one, so the search ends and JavaScript throws. This is the same ReferenceError you met in unit 2, now with a fuller explanation: the name was not in any scope along the chain from where the code was written.
Pro Tip: Because the chain is fixed by position, you can determine what any function can see by reading inwards from the top of the file. No execution required, no debugger, no guessing about call order.
EXERCISE
3Local Beats Global: Variable Priority
When a variable exists in both local and outer scope with the same name, the local one always wins. JavaScript always checks the closest scope first.
When two variables share a name, the one declared closest to where you are reading wins. JavaScript looks in the current scope first, and only searches outward if the name is not found there. It stops at the first match, which means an inner declaration hides an outer one of the same name for as long as the inner scope lasts.
const score = 100;
function showScore() {
const score = 999;
console.log(score); // 999
}
showScore();
console.log(score); // 100
Two independent variables that happen to share a name. The one inside the function is found first, so the outer one is never reached from in there. Crucially, the outer one is unchanged afterwards: nothing was overwritten, because these are two separate bindings in two separate scopes.
That independence holds across sibling scopes too:
const x = 1;
function a() {
const x = 10;
console.log(x); // 10
}
function b() {
const x = 100;
console.log(x); // 100
}
a();
b();
console.log(x); // 1
Three bindings named x, none of which can see the others. a cannot reach into b, and neither can touch the outer one.
Leaving out the declaration changes everything:
let count = 0;
function increment() {
count = count + 1;
}
increment();
increment();
console.log(count); // 2
There is no let or const inside increment, so count is not a new binding. The lookup walks outward, finds the existing count, and assigns to that. The function is now modifying state that lives outside it.
Both behaviours are correct and both are useful, but the difference between them is a single keyword. A missing const turns a private variable into a shared one, and the code looks almost identical either way. When a value is changing and you cannot work out who is changing it, this is the first thing worth checking.
The shadowed name does not have to hold the same kind of value either, which can make the effect harder to spot:
const items = ["a", "b", "c"];
function count() {
const items = 3;
return items;
}
console.log(count()); // 3
console.log(items); // ["a", "b", "c"]
Inside count, the name items refers to a number. Outside it, the same name refers to an array. Both are correct, and anyone reading only one of the two functions would reasonably assume the wrong type. Reusing a name from an enclosing scope for something unrelated is legal and almost always worth avoiding.
