Sub topic 2
Shadowing Variables in Inner Scopes
This chapter assumes you know basic JavaScript syntax and how to declare variables and functions. It also assumes you have already seen how the scope chain resolves names.
Shadowing Variables in Inner Scopes
Shadowing happens when an inner scope declares a name that an outer scope already uses. Lookup walks outward through the scope chain and stops at the nearest declaration, so the inner name hides the outer one.
const level = "global";
function outer() {
const level = "outer";
function inner() {
return level;
}
return inner();
}
console.log(outer()); // "outer"
console.log(level); // "global"Shadowing never changes the outer variable. A common mistake is to shadow a variable by accident and then wonder why an update "didn't stick". Linters can warn about this with the no-shadow rule.
Creation and Execution: Why Hoisting Happens
JavaScript processes each scope in two phases:
- Creation phase. The engine scans the scope and registers every declaration before any line runs.
- Execution phase. The code runs top to bottom, and assignments happen in order.
Because names are registered first, a name can exist before the line that declares it. This behavior is called hoisting.
Hoisting var Declarations
During the creation phase, a var is registered and initialized to undefined. Its assignment stays where you wrote it.
console.log(x); // undefined
var x = 5;
console.log(x); // 5The code does not crash. It quietly gives you undefined, which is why var bugs are hard to spot.
Function Declarations Versus Function Expressions
A function declaration is hoisted together with its body, so you can call it before it appears. A function expression assigned to var hoists only the variable, so calling it early means calling undefined.
greet(); // "hi"
function greet() {
console.log("hi");
}
try {
sayBye();
} catch (e) {
console.log(e.name); // "TypeError"
}
var sayBye = function () {
console.log("bye");
};| Form | Hoisted name | Early call result |
|---|---|---|
| `function f() {}` | Name and body | Works |
| `var f = function () {}` | Name only (`undefined`) | `TypeError` |
Exercise
What does this code print, and why? var n = 1; function show() { console.log(n); var n = 2; } show();
Show answer
It prints undefined. Inside show, the local var n is hoisted to the top of the function and initialized to undefined. It shadows the global n, and the assignment n = 2 runs only after the console.log call.