본문으로 건너뛰기

Scope

Scope

In JavaScript, the scope refers to the range where variables, functions, and objects can be accessed.

Scope determines which parts of the code can access certain variables. JavaScript has several different rules for scope as follows.


Types

Global Scope: Variables declared in the outermost part of the code have global scope. Global variables can be accessed from anywhere.

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

Local Scope: Variables declared inside a function are accessible only within that function and not outside of it. These are called local variables.

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

function myFunction() {
let localVar = "I'm a local variable!"; // Local variable
console.log(globalVar); // Accessing a global variable from inside 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, which means they are only accessible within the block ({}) where they are defined.

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

Points to Note

  • Variables declared with var do not have block scope; instead, they have function scope.

Example

JavaScript
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 a variable is "visible" and "usable". Understanding the rules of scope is essential to prevent errors in your code.