Skip to content

Scope

Medium — good to knowFrontend

ELI5 — The Vibe Check

Scope is about where your variables are visible. Variables defined inside a function can't be seen outside it (that's function scope). Variables defined with let/const inside {} blocks have block scope. Variables at the top of the file are global and visible everywhere (usually a bad idea).

Real Talk

Scope in JavaScript determines the accessibility of variables. ES6 introduced block-scoped let and const (accessible within the nearest {} block), complementing function scope (var, accessible within the enclosing function) and global scope. JavaScript uses lexical (static) scoping — scope is determined at write time, not runtime.

Show Me The Code

const globalVar = 'I am global'

function outer() {
  const outerVar = 'I am outer'

  function inner() {
    const innerVar = 'I am inner'
    console.log(globalVar) // accessible
    console.log(outerVar)  // accessible (closure)
    console.log(innerVar)  // accessible
  }

  // console.log(innerVar) // ReferenceError!
}

When You'll Hear This

Prefer const and let over var for predictable block scoping.,Accidental global variables are a common source of bugs.,Understanding scope is key to understanding closures.

Made with passive-aggressive love by manoga.digital. Powered by Claude.