Scope and Visibility
Understand variable scope — global, function, and block scope — and how visibility controls access in your code.
What you'll learn
- What scope is and why it prevents naming conflicts
- The difference between global, function, and block scope
- How let/const and var differ in scoping behavior
- What closures are and how they capture scope
- Best practices for keeping scope as narrow as possible
Concept
Scope and Visibility
Scope is the region of your program where a variable is accessible. It determines where a name is valid and where it is not. Scope is a protective mechanism: it prevents variables from colliding with each other and keeps the program organized by limiting where each name has meaning.
Three Levels of Scope
JavaScript has three main levels of scope:
- Global scope — variables declared outside any function or block. They are accessible everywhere, which sounds convenient but is dangerous: any part of the program can change them, making bugs hard to trace.
- Function scope — variables declared inside a function. They exist only within that function and are destroyed when it returns. This is the natural boundary for most variables.
- Block scope — variables declared with
letorconstinside a block ({}). They exist only within that block. A block can be anifbody, aforloop, or any pair of braces.
const global = "I am everywhere";
function example() {
const functionScoped = "I exist only in example()";
if (true) {
const blockScoped = "I exist only in this if-block";
console.log(global, functionScoped, blockScoped); // all accessible
}
// console.log(blockScoped); // ReferenceError — out of scope
}
let/const vs. var
The older var keyword has function scope, not block scope. A var declared inside an if block leaks out to the entire function. This is a major source of bugs, which is why modern JavaScript uses let and const exclusively — both are block-scoped and behave predictably.
function demo() {
if (true) {
var oldWay = "leaks out"; // function-scoped
let newWay = "stays in"; // block-scoped
}
console.log(oldWay); // "leaks out" — var ignored the block
// console.log(newWay); // ReferenceError — let respected the block
}
Closures
A closure is a function that "remembers" the scope where it was created, even after that scope has finished executing. This is how you create private data and stateful functions in JavaScript:
function makeCounter() {
let count = 0; // private — only accessible via the returned function
return function () {
count++;
return count;
};
}
const counter = makeCounter();
counter(); // 1
counter(); // 2 — the count variable persists
Keep Scope Narrow
A general principle: declare variables in the narrowest scope that works. If a variable is only needed inside a loop, declare it inside the loop. If it is only needed in an if block, declare it there. Narrow scope reduces naming conflicts, makes variables easier to reason about, and helps the compiler optimize. Global variables should be rare and intentional — each one is a potential source of subtle bugs.
Example
// Demonstrate all three scope levels
const appName = "MyApp"; // global scope
function createUser(name) {
const userId = Math.floor(Math.random() * 1000); // function scope
// Block scope inside a conditional
if (name.length > 0) {
const displayName = name.trim(); // block scope
console.log(`Creating ${displayName} for ${appName}`);
}
// displayName is not accessible here — it was block-scoped
return { id: userId, name: name };
}
// Closure: a function factory that captures private state
function makeAccount(initialBalance) {
let balance = initialBalance; // private — captured by closure
return {
deposit(amount) { balance += amount; return balance; },
withdraw(amount) {
if (amount > balance) throw new Error("Insufficient funds");
balance -= amount;
return balance;
},
getBalance() { return balance; },
};
}
const account = makeAccount(100);
account.deposit(50); // balance is now 150
account.withdraw(30); // balance is now 120
console.log(account.getBalance()); // 120
// console.log(balance); // ReferenceError — balance is private
The createUser function shows global, function, and block scope. The makeAccount factory uses a closure to keep balance private — it can only be accessed through the deposit, withdraw, and getBalance methods.
Try it
- JSON Formatter
JSON structure mirrors scope: nested objects create nested visibility. See how data is organized hierarchically.
- Code Minifier
Minifiers rename variables to short names within their scope — a practical demonstration of scope boundaries.
Common mistakes
The mistake
Using var instead of let/const, causing variables to leak out of blocks.
The fix
Always use let (for reassignable) or const (for fixed) instead of var. var has confusing function-scoping that leads to bugs. Modern code should never use var.
The mistake
Declaring all variables at the top of a function 'just in case'.
The fix
Declare variables where they are first needed, in the narrowest scope. This makes them easier to find, reduces their lifetime, and prevents accidental use before initialization.
The mistake
Creating global variables without realizing it (forgetting let/const).
The fix
Always use let or const. Writing x = 5 without a keyword creates a global variable in non-strict mode. Enable 'use strict' to catch this mistake as an error.
Related Resources
Related Cheatsheets
- JavaScript Cheatsheet
Reference for scoping rules, var vs let vs const, and closure patterns.
Practice Scope and Visibility
8 exercises
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.