Scope
In JavaScript, scope refers to the range
in which variables, functions, and objects can be accessed.
Scope determines where in the code you can access certain variables. JavaScript has several scope rules as outlined below.
Global Scope: A variable with global scope can be accessed from anywhere in the code. These variables are declared at the top level, outside of functions or blocks (e.g., surrounded by {}
).
// Declare a global variable
var message = 'Hello, World!';
// Access the global variable
console.log(message); // Output: Hello, World!
function showMessage() {
message = 'Hello, JavaScript!'; // Modify the global variable
console.log(message); // Access the global variable
}
// Call the showMessage function
showMessage(); // Output: Hello, JavaScript!
Local Scope: Local scope refers to the scope within a function or a block of code where the variable is declared.
A local variable, which has local scope, is declared inside a function or block and can only be accessed within that function or block, thus preventing conflicts with other parts of the program.
let globalVar = "I'm a global variable!"; // Global variable
function myFunction() {
let localVar = "I'm a local variable!"; // Local variable
console.log(globalVar); // Global variable can be accessed within the function
}
console.log(localVar); // Error: localVar is only accessible within myFunction
Block Scope: Variables declared with the let
and const
keywords have block scope, meaning they can only be accessed within the block (e.g., {}
) where they are declared. Variables declared with let
can be reassigned, while variables declared with const
cannot be reassigned.
if (true) {
let blockVar = "I'm inside a block!"; // Block scope
console.log(blockVar); // Can access within the block
}
console.log(blockVar); // Error: blockVar is only accessible within the block
Cautions
- Variables declared with
var
do not have block scope but have function scope.
Example
let outerVar = "I'm outside!";
function myFunction() {
let innerVar = "I'm inside!";
console.log(outerVar); // I'm outside!
console.log(innerVar); // I'm inside!
}
myFunction();
console.log(outerVar); // I'm outside!
console.log(innerVar); // Error! innerVar is only accessible within myFunction
Scope determines where variables are "visible" and "usable."
Understanding scope rules is crucial to avoid errors in your code.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.