← Back to Roadmap

Variable Scope

Medium

In plain terms

Scope determines where a variable is accessible. Block scope: let/const inside { }. Function scope: var inside function. Global scope: outermost level. Inner scopes can access outer; not vice versa.

What you need to know

  • Block: let/const in {}
  • Function: var in function
  • Lexical: inner sees outer

Try it yourself

Copy the code below and run it in your browser console or a code editor:

const global = 'I am global';

function foo() {
  const functionScoped = 'in function';
  if (true) {
    const blockScoped = 'in block';
    console.log(blockScoped);  // OK
  }
  // console.log(blockScoped);  // Error
}

// Lexical scope - nested functions see outer
function outer() {
  const x = 1;
  function inner() {
    console.log(x);  // 1 - from outer
  }
  inner();
}

Learn more

Dive deeper with these trusted resources: