JavaScript Scope
What is Scope?โ
Scope determines where variables can be accessed in your code. JavaScript uses lexical scoping - the position where variables are declared determines their accessibility.
Types of Scopeโ
1. Global Scopeโ
Variables declared outside any function or block:
var globalVar = "I'm global";
let globalLet = "Also global";
function test() {
console.log(globalVar); // Accessible everywhere
}
2. Function Scopeโ
Variables declared inside a function:
function myFunction() {
var functionScoped = "Only inside function";
console.log(functionScoped); // Works
}
// console.log(functionScoped); // Error: not defined
3. Block Scopeโ
Variables declared inside {} blocks (let/const only):
if (true) {
let blockScoped = "Only in this block";
var functionScoped = "Available in entire function";
}
// console.log(blockScoped); // Error: not defined
console.log(functionScoped); // Works (var ignores block scope)
Scope Chainโ
JavaScript looks for variables from inner to outer scope:
var x = "global";
function outer() {
var x = "outer";
function inner() {
var x = "inner";
console.log(x); // "inner" (finds closest scope)
}
inner();
console.log(x); // "outer"
}
outer();
console.log(x); // "global"
Key Rulesโ
- Inner scopes can access outer scope variables
- Outer scopes cannot access inner scope variables
- Variables are searched from innermost to outermost scope
varis function-scoped,let/constare block-scoped