Scope
Scope is the set of rules deciding where a variable can be seen from, and it is what keeps the names in one function from colliding with another.
Every function and every block creates a scope. Inner code can read outward, outer code cannot read inward, and a name declared inside shadows the same name outside. let and const respect blocks; var does not.
EXERCISE
1Where a Variable Can Be Seen
A variable declared inside a function exists only inside it, which is what makes functions safe to write independently.
Scope is the region of code in which a name can be read. A variable declared inside a block is visible inside that block, and inside anything nested within it. From outside that block the name does not exist at all, and reading it is an error rather than a value.
Function scope:
const siteName = "DevLoom"; // the hallway: global
function greet() {
const message = "Hello"; // inside the room
console.log(message); // Hello
console.log(siteName); // DevLoom <- can see outward
}
greet();
console.log(message); // ReferenceError: message is not defined
Two functions cannot see each other's variables:
function first() {
const secret = "one";
}
function second() {
console.log(secret); // ReferenceError: secret is not defined
}
// This is a feature. It means you can name a variable `i` or `total`
// inside a function without checking what every other function used.
Block scope, which is any pair of braces:
if (true) {
const inside = "block";
console.log(inside); // block
}
console.log(inside); // ReferenceError
for (let i = 0; i < 3; i++) {
// i lives only here
}
console.log(i); // ReferenceError
And the one that does not respect blocks:
if (true) {
var leaky = "I escape";
let contained = "I do not";
}
console.log(leaky); // I escape
console.log(contained); // ReferenceError
// var is scoped to the FUNCTION, not the block.
// One more reason const and let replaced it.
Scope is the reason you can write a function without reading the rest of the file first. Every name you declare inside is yours alone, and nothing outside can see it or be broken by it. That guarantee is what makes it possible to build a program out of parts rather than one long script.
EXERCISE
2The Scope Chain and Shadowing
When a name is used, JavaScript looks outward one level at a time until it finds it, and a closer declaration hides a further one.
Looking outward, level by level:
const level = "global";
function outer() {
const outerVar = "outer";
function inner() {
console.log(outerVar); // found one level out
console.log(level); // found two levels out
}
inner();
}
outer();
// outer
// global
The search only ever goes outward. If it reaches the outermost level without finding the name, you get a ReferenceError.
Shadowing: a nearer name wins:
const name = "global Ada";
function show() {
const name = "local Grace";
console.log(name); // local Grace <- the nearer one
}
show();
console.log(name); // global Ada <- untouched
Which is usually fine, and occasionally confusing:
const total = 100;
function calculate(items) {
let total = 0; // deliberately shadows, and that is fine
for (const item of items) {
total += item.price;
}
return total;
}
console.log(calculate([{ price: 30 }, { price: 20 }])); // 50
console.log(total); // 100
A parameter shadows too:
const user = "outer user";
function show(user) {
console.log(user); // whatever was passed in
}
show("inner user"); // inner user
Pro Tip: Shadowing is not a mistake, it is how local names stay local. It becomes a problem only when the shadowed name is one you actually meant to use, and the symptom is a variable that mysteriously holds the wrong value. If a function is long enough that you cannot see both declarations at once, that is a sign the function wants splitting.
EXERCISE
3Why Global Variables Cause Trouble
A variable at the top level is visible to every function in your program, which sounds convenient until two of them disagree about it.
The convenience:
let currentUser = null;
function logIn(name) {
currentUser = name;
}
function showHeader() {
console.log(currentUser ? `Hi ${currentUser}` : "Sign in");
}
logIn("Ada");
showHeader(); // Hi Ada
The trouble, which arrives later:
// Six months on, someone adds this:
function resetForm() {
currentUser = null; // reasonable in isolation
}
// And now showHeader sometimes prints "Sign in" after a login,
// depending on the order things happened in.
// Nothing in showHeader is wrong. It cannot be debugged by reading it.
The same logic with the value passed in:
function showHeader(user) {
console.log(user ? `Hi ${user}` : "Sign in");
}
showHeader("Ada"); // Hi Ada
showHeader(null); // Sign in
// Now the function's output depends only on its input.
// You can test it, move it, and reason about it on its own.
Accidental globals, which are worse:
function calculate() {
result = 42; // no const, no let, no var
}
calculate();
console.log(result); // 42 <- a global you never declared
// In strict mode, which modules use by default, this throws:
// ReferenceError: result is not defined
Pro Tip: Prefer passing values in and returning values out over reaching for a shared variable. A function whose answer depends only on its arguments can be understood by reading it alone, and that property is worth more than the few keystrokes a global saves. Keep the top level for genuine constants like a site name or an API base URL.
