Variable Scopes in JavaScript

🔍 What is Scope?

Scope in JavaScript determines the accessibility or visibility of variables. It answers the question: "Where can this variable be accessed?"

🌍 1. Global Scope

A variable declared outside of all functions or blocks has global scope and is accessible anywhere in the code.

Code Snippet

var globalVar = "I'm global";

function show() {
  console.log(globalVar); // ✅ Accessible
}
show();

🧩 2. Function Scope

Variables declared inside a function (using var, let, or const) are only accessible within that function.

Code Snippet

function greet() {
  var message = "Hello";
  console.log(message); // ✅ Accessible
}
greet();
console.log(message); // ❌ ReferenceError

📦 3. Block Scope

Only let and const are block-scoped — they exist only within the nearest pair of curly braces .

Code Snippet

if (true) {
  let name = "Sathish";
  const age = 25;
}
console.log(name); // ❌ ReferenceError
console.log(age);  // ❌ ReferenceError

Note

var is NOT block-scoped. It is function-scoped!

Code Snippet

if (true) {
  var visible = "Yes";
}
console.log(visible); // ✅ Yes

🧠 4. Lexical Scope

Lexical (or static) scope means that a function can access variables from the scope where it was defined, not where it's called.

Code Snippet

function outer() {
  let outerVar = "Outer";

  function inner() {
    console.log(outerVar); // ✅ Outer
  }

  inner();
}
outer();

🔄 Scope Chain

When looking for a variable, JavaScript first checks the local scope, then moves outward to the parent scopes — this is known as the scope chain.

🎯 Summary

  • Global Scope: Accessible everywhere.
  • Function Scope: Declared inside a function; accessible only there.
  • Block Scope: Works with let and const inside blocks.
  • Lexical Scope: Functions remember where they were defined.
>>“Understanding scope is key to avoiding bugs and writing clean code.”

🔗 References