JavaScript Scope Explained


In JavaScript, scope defines where variables are accessible. Understanding scope is crucial for writing clean, bug-free, and maintainable code.



Types of JavaScript Scope


1. Global Scope


A variable declared outside any function or block is in the global scope. It can be accessed anywhere in the code.

Example:

let globalVar = "I am global";

function showGlobal() {
  console.log(globalVar);
}

showGlobal();

Output

I am global

Avoid polluting global scope—too many global variables can lead to bugs.



2. Local (Function) Scope


Variables declared inside a function using var, let, or const are local to that function.

Example:

function greet() {
  let localVar = "I am local";
  console.log(localVar);
}

greet();
// console.log(localVar);  Error: localVar is not defined

Output

I am local


3. Block Scope (let and const only)


Variables declared inside a block ({}), such as inside if, for, or while, are only accessible within that block.

Example:

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

// console.log(blockVar);  Error: blockVar is not defined

Output

I am block-scoped

var is NOT block-scoped – it's function-scoped, which can lead to bugs.


example:

if (true) {
  var testVar = "Not block scoped";
}
console.log(testVar); //  Still accessible outside the block

Output

Not block scoped


Scope Table Summary

Scope Type Declared With Accessible Where?
Global Scope var, let, const (outside any function) Anywhere in the file or script
Function Scope var, let, const (inside a function) Only inside that function
Block Scope let, const (inside {}) Only inside the block (e.g., if/loop)