Scope refers to the context in which variables and functions are declared and accessed in JavaScript. It determines the visibility and lifetime of these identifiers.
Variables declared outside of any function or block have global scope, making them accessible from anywhere in the script.
let globalVariable = "I am global";
function printGlobal() {
console.log(globalVariable); // Accessible inside the function
}
printGlobal()
console.log(globalVariable); // Accessible outside the function
Variables declared within a function have local scope, meaning they are only accessible within that function.
function scopeExample() {
var localVar = "I'm local!";
console.log(localVar); // Outputs: I'm local! (Accessible)
}
scopeExample()
console.log(localVar); // Error: localVar is not defined. (Not accessible)
Introduced in ES6, let and const have block scope, meaning they are confined to the nearest enclosing block (e.g., if, for, or {}).
function exampleFunction() {
if (true) {
var x = 10; // Function-scoped variable
let y = 20; // Block-scoped variable
const z = 30; // Block-scoped variable
}
console.log(x); // Outputs 10, x is accessible due to function scope
console.log(y); // Throws an error, y is not accessible outside the block
console.log(z); // Throws an error, z is not accessible outside the block
}
exampleFunction();
JavaScript uses a scope chain to resolve variable names. If a variable is not found in the current scope, the engine looks up the chain until it finds the variable or reaches the global scope.
let x = 40;
function outer() {
let y = 50;
function inner() {
let z = 60;
console.log(x + y + z); // Accessible: 150
}
inner();
}
outer();
console.log(x + y); // Not accessible
Variables declared without var, let, or const become global variables, even if declared inside a function.
function createGlobalVar() {
globalVar = 80; // Becomes a global variable
}
createGlobalVar();
console.log(globalVar); // Accessible: 80
Understanding JavaScript scopes is crucial for managing variables and functions effectively. Scopes define where identifiers are accessible and help prevent naming conflicts.