DEV Community

Cover image for Understanding JavaScript Scope (With Examples)
Suvankarr Dash
Suvankarr Dash

Posted on

Understanding JavaScript Scope (With Examples)

What Is Scope in JavaScript?

  • Scope defines where variables and functions are visible and accessible in your code.
  • JavaScript scope rules directly affect safety, memory usage, and bug prevention.

  • Modern JavaScript has five key scope concepts you must understand.

1️⃣ Global Scope:

Definition:

  • Variables declared outside any function or block.

code:
var g = 1; // becomes window.g (browser)
let h = 2; // global but not a window property

  • ⚠️ Overusing global scope leads to name collisions and hard-to-debug issues.
  • ✅ Prefer modules for app-wide values.

2️⃣ Block Scope:

Definition:

  • Variables declared with let or const exist only inside { }.

code:
if (true) {
let x = 10;
}
console.log(x); // ReferenceError

  • ✅ Best for loops, conditionals, and temporary values.

3️⃣ Lexical Scope (Closures):

Definition:

  • Scope is determined by where variables/functions are written in the source code.

code:
function makeCounter() {
let count = 0;
return () => ++count;
}

const counter = makeCounter();
counter(); // 1

  • ✅ Enables private state, encapsulation, and functional patterns.

4️⃣ Window Scope (Browser):

Definition:

  • In browsers, window is the global object.

code:
var a = 1;
console.log(window.a); // 1

let b = 2;
console.log(window.b); // undefined

  • ⚠️ Mostly legacy behavior — avoid in modern apps .

5️⃣ Hoisting:

Definition:

  • Declarations are processed before execution.

code:
console.log(a); // undefined
var a = 5;

console.log(b); // ReferenceError
let b = 6;

  • var → hoisted + initialized
  • let/const → hoisted but blocked by Temporal Dead Zone

✅ Best Practices:

  • Prefer const → let → avoid var
  • Never rely on implicit globals
  • Use ES modules to isolate scope
  • Read legacy code carefully due to hoisting

Top comments (0)