JavaScript - Variable Scope

Overview

Estimated time: 15–25 minutes

Scope defines where a variable is visible. Prefer block-scoped let/const.

Learning Objectives

  • Differentiate global, function, and block scope.
  • Predict where variables are accessible.

Prerequisites

Block vs function scope

function f(){
  if (true) {
    let a = 1;     // block
    var b = 2;     // function
  }
  // console.log(a); // ReferenceError
  console.log(b);   // 2
}

Global scope

// In browsers, globals attach to window (or globalThis)
let x = 1; // not a property of window
var y = 2; // window.y === 2

Common Pitfalls

  • Accidentally creating globals by assigning undeclared variables (prevented in strict mode).