This site uses tracking technologies. You may opt in or opt out of the use of these technologies.

Back to Javascript

Javascript Scope (local vs. global)

In JavaScript, scope refers to the context in which variables and functions are accessible. The two main types of scope are global and local (block or function).

1. Global Scope

  • Definition: Variables declared outside of any function or block are in the global scope.

  • Access: Globally scoped variables can be accessed and modified from anywhere in the code.

  • Example:

let globalVar = "I am global";
function showGlobal() {
console.log(globalVar); // Accessible here
}
showGlobal(); // Outputs: "I am global"
console.log(globalVar); // Accessible here too

2. Local Scope

Local scope is further split into function scope and block scope:

Function Scope

  • Definition: Variables declared within a function are scoped to that function.

  • Access: They can only be accessed from within that function.

  • Example:

function showLocal() {
let localVar = "I am local";
console.log(localVar); // Accessible here
}
showLocal(); // Outputs: "I am local"
console.log(localVar); // Error: localVar is not defined

Block Scope (ES6 and later)

  • Definition: Variables declared with let or const within a {} block are scoped to that block.

  • Access: These variables are only accessible inside the block, unlike var, which doesn’t respect block scope.

  • Example:

if (true) {
let blockVar = "I am block-scoped";
console.log(blockVar); // Accessible here
}
console.log(blockVar); // Error: blockVar is not defined

Summary of Scope Rules

  • Global variables are accessible from anywhere in the code.

  • Function-scoped variables (using var, let, or const) are only accessible within the function they’re defined in.

  • Block-scoped variables (using let or const) are only accessible within the block they’re defined in.

Understanding scope helps prevent bugs, especially with naming conflicts and accidental overwriting of values.