When JavaScript sees a variable name, how does it find the right box? It follows a simple rule: start in the current scope and look outward, one level at a time, until it finds the variable. If it reaches the global scope and still hasn't found it, you get a ReferenceError.
This path is called the scope chain:
const planet = "Earth";
function country() {
const nation = "France";
function city() {
const town = "Paris";
console.log(`${town}, ${nation}, ${planet}`);
}
city();
}
country();
It prints
Paris, France, Earth
When city needs town, it finds it right in its own scope. For nation, it doesn't find it locally, so it looks one level out, in country, and finds it there. For planet, it looks out again, all the way to the global scope.
The lookup only ever goes outward, never inward. country can't see town, and the global scope can't see nation. One-way windows, remember?