JavaScript Scope
Scope determines where variables are accessible. JavaScript has three types of scope: Global, Function, and Block.
Global Scope
Variables declared outside any function or block are in the global scope. They are accessible from anywhere in the script.
Global Scope
let globalVar = "I am global";
function showGlobal() {
console.log(globalVar); // accessible inside function
}
showGlobal();
console.log(globalVar); // accessible outside tooFunction Scope
Variables declared inside a function are local to that function. They cannot be accessed from outside.
Function Scope
function greet() {
let message = "Hello!"; // local to greet()
console.log(message);
}
greet();
// console.log(message); // ReferenceError — not accessible hereBlock Scope (let and const)
Variables declared with let or const inside a block ({}) are only accessible within that block.
Block Scope
if (true) {
let blockVar = "block scoped";
const blockConst = "also block scoped";
console.log(blockVar); // OK inside block
}
// console.log(blockVar); // ReferenceError outside blockThe Scope Chain
Inner scopes can access outer scope variables, but outer scopes cannot access inner scope variables.
Scope Chain
let outer = "outer";
function middle() {
let mid = "middle";
function inner() {
let innerVar = "inner";
console.log(outer); // ✓ can access outer
console.log(mid); // ✓ can access middle
console.log(innerVar); // ✓ can access own
}
inner();
// console.log(innerVar); // ✗ ReferenceError
}
middle();Variable Shadowing
When an inner scope declares a variable with the same name as an outer scope variable, it shadows the outer one.
Shadowing
let color = "red";
function paint() {
let color = "blue"; // shadows outer 'color'
console.log(color); // "blue"
}
paint();
console.log(color); // "red" — outer unchanged| Scope | Declared With | Accessible From |
|---|---|---|
| Global | Outside all blocks | Anywhere in the script |
| Function | Inside a function | Only within that function |
| Block | let/const in a block | Only within that block |
📝 Note: var does NOT respect block scope — it leaks out of if/for blocks. Always use let or const for predictable scoping.
Exercise:
Variables declared outside any function or block have which scope?