Scoping determines the accessibility (visibility) of variables at different parts of your code.
Types of Scope in JavaScript
Global Scope: Variables declared outside any function or block are in the global scope. They can be accessed from anywhere in the code.
let globalVariable = "I'm global!";
function accessGlobal() {
console.log(globalVariable); // Accessible
}
accessGlobal(); // Output: I'm global!
console.log(globalVariable); // Output: I'm global!
Function Scope: Variables declared inside a function using var
, let
, or const
are accessible only within that function.
function exampleFunction() {
var functionScoped = "I'm only accessible within this function.";
console.log(functionScoped); // Output: I'm only accessible within this function.
}
exampleFunction();
console.log(functionScoped); // Error: functionScoped is not defined
Block Scope: Variables declared with let
or const
are block-scoped, meaning they are accessible only within the block ({ ... }
) in which they are defined.
{
let blockScoped = "I'm block-scoped!";
console.log(blockScoped); // Output: I'm block-scoped!
}
console.log(blockScoped); // Error: blockScoped is not defined
let
and const
respect block scoping.var
does not respect block scoping—it is only function-scoped or globally scoped.{
var notBlockScoped = "I'm not block-scoped!";
}
console.log(notBlockScoped); // Output: I'm not block-scoped!