JavaScript scopes
Scope decides where in your code a variable can be seen and used. A variable declared inside a function is not visible outside it, and one declared inside a block with let or const exists only within that block. Understanding scope prevents name clashes, mysterious ReferenceErrors and bugs where one part of a program accidentally changes another part's data.
The three levels of scope
- Global scope: variables declared outside any function or block. They are visible everywhere in the script, which makes them convenient but risky, since any code can change them.
- Function scope: variables declared inside a function, including its parameters, are visible only inside that function. Each call gets a fresh set.
- Block scope: variables declared with
letorconstinside curly braces, such as anif,foror plain{ }block, exist only inside those braces.
Modules add one more: in an ES module, top-level variables belong to that module only, not to the whole page.
var ignores blocks
The old var keyword is function scoped, not block scoped. A var declared inside an if or for leaks out into the whole function. This is one of the main reasons modern code uses let and const.
function demo() {
if (true) {
var a = 'var';
let b = 'let';
const c = 'const';
}
console.log(a); // 'var': leaked out of the block
console.log(b); // ReferenceError: b is not defined
}
const appName = 'Notes'; // global
function outer() {
const user = 'Meera'; // outer's scope
function inner() {
const note = 'Buy books'; // inner's scope
console.log(appName, user, note); // all visible
}
inner();
console.log(note); // ReferenceError
}
Lexical scope and the scope chain
JavaScript uses lexical scope: what a function can see depends on where it is written in the code, not where it is called from. When code uses a variable, the engine looks in the current scope first, then the enclosing scope, then the next one out, all the way to global. This lookup path is the scope chain. Inner functions can read outer variables, but outer code can never reach into an inner function's variables.
If an inner scope declares a variable with the same name as an outer one, the inner one shadows it. Inside that scope, the outer variable is hidden. Shadowing is legal but can make code confusing, so use distinct names when you can.
The temporal dead zone
let and const variables exist from the start of their block but cannot be used until the line where they are declared. Accessing them earlier throws a ReferenceError. This region is called the temporal dead zone. With var, the same early access silently gives undefined, which hides mistakes.
The loop bug that scope explains
This classic example prints 3, 3, 3 instead of 0, 1, 2:
for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100); }
Because var is function scoped, there is only one i, and by the time the timers fire the loop has finished and i is 3. Changing var to let fixes it, since let creates a new binding of i for each loop iteration. Each callback remembers its own copy. This "remembering" is exactly what the next lesson on closures explores.
Another frequent issue is assigning to a variable that was never declared. In non-strict code this silently creates a global variable. Strict mode, used automatically in modules and classes, throws an error instead.
Rules of thumb
- Declare variables in the smallest scope that needs them.
- Use
constby default,letwhen you reassign, and avoidvar. - Keep globals to a minimum to avoid clashes between scripts.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.