Skip to main content
Practice

Scope

In JavaScript, the scope is the range within which variables, functions, and objects can be accessed.

The scope determines what parts of your code can access certain variables. In JavaScript, there are several scope rules as described below.


Global Scope: Variables declared in the global scope can be accessed from anywhere in your code. These variables are declared at the top level, not inside any function or block wrapped in curly braces ({}).

Global Variable
// Declare a global variable
var message = 'Hello, World!';

// Output the global variable
console.log(message); // Output: Hello, World!

function showMessage() {
message = 'Hello, JavaScript!'; // Change the global variable's value
console.log(message); // Output the message variable value
}

// Call the showMessage function
showMessage(); // Output: Hello, JavaScript!

Local Scope: Local scope refers to the region in which a variable is only accessible within the function or block in which it is declared.

Local variables in a local scope are declared inside a function or block and can only be accessed and used within that scope, preventing conflicts with other parts of the program.

Local Variable and Global Variable
let globalVar = "I'm a global variable!"; // Global variable

function myFunction() {
let localVar = "I'm a local variable!"; // Local variable
console.log(globalVar); // Accessing global variable inside the function
}

console.log(localVar); // Error: localVar is only accessible inside myFunction

Block Scope: Variables declared with let and const have block scope, meaning they can only be accessed within the block ({}) they are declared in. Variables declared with let can be reassigned, whereas those declared with const cannot be reassigned.

Block Scope
if (true) {
let blockVar = "I'm inside a block!"; // Block scope
console.log(blockVar); // Accessible within the block
}
console.log(blockVar); // Error: blockVar is only accessible within the block

Notes

  • Variables declared with var do not have block scope but have function scope.

Example

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.

The scope determines where a variable can be "seen" and "used."

Understanding scope rules is essential to avoid errors in your code.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.