Course contentsShow
← JavaScript
Lesson 89 of 2,7233. Variables and ScopeFree lesson

Best Practices for Scope

Prefer block scope with let/const, minimize global variables, and keep scope tight.

Best Practices for Scope

You'll learn how to write cleaner, safer JavaScript by following scope best practices that prevent common bugs.

Why Scope Discipline Matters

Think of scope like organizing your kitchen: you wouldn't store everything on the counter (global scope) or hide everything in a locked pantry (overly tight scope). You want the right balance—items accessible where needed, but not cluttering the workspace.

Three Golden Rules

1. Prefer let and const Over var

Always choose block-scoped variables (let/const) instead of function-scoped var. They're more predictable and prevent accidental bugs from hoisting and loop issues.

// ✅ Good
if (true) {
  let message = "Hello";
  console.log(message);
}
// message is gone here

// ❌ Avoid
if (true) {
  var leaky = "Oops";
}
console.log(leaky); // Still accessible!

2. Minimize Global Variables

Global scope is like a public bulletin board—everyone can access and modify it. Keep it clean by declaring variables only where needed.

// ❌ Pollutes global scope
let userName = "Alice";

// ✅ Keep it local
function greetUser() {
  let userName = "Alice";
  console.log(userName);
}

3. Keep Scope as Tight as Possible

Declare variables in the smallest scope necessary. This reduces naming conflicts, makes code easier to understand, and helps prevent unintended modifications.

function processData() {
  // ❌ Declared too early
  let result;
  let temp;
  // ...100 lines later...
  result = calculate();
  
  // ✅ Declare close to use
  // ...code...
  let result = calculate();
}

Key Takeaway: Use let/const for block scope, avoid cluttering global scope, and declare variables in the tightest scope possible—your future self will thank you for cleaner, less buggy code.