Codectionary / Developer documentation / JavaScript

Scope

Scope determines where variables are accessible in your code. JavaScript has global scope (accessible everywhere), function scope (var-declared variables inside a function), and block scope (let/const-declared variables inside any { } block, including if statements and loops). Inner scopes can access outer scope variables, but not vice versa.

Syntax

{ /* block scope */ }
function() { /* function scope */ }

Examples

Global vs Function Scope

Variables declared at the top level vs inside a function.

const globalVar = "I am global";

function myFunction() {
  const localVar = "I am local";
  console.log(globalVar); // accessible - inner scope sees outer scope
  console.log(localVar);
}

myFunction();
// console.log(localVar); // ReferenceError - not accessible outside the function

Block Scope with let/const

let and const respect block boundaries, unlike var.

if (true) {
  let blockScoped = "only visible in this block";
  var functionScoped = "visible outside the block";
}

// console.log(blockScoped);  // ReferenceError
console.log(functionScoped); // works - var ignores block boundaries

Scope Chain

Nested functions can access variables from every enclosing scope.

const outer = "outer value";

function level1() {
  const middle = "middle value";
  function level2() {
    const inner = "inner value";
    console.log(outer, middle, inner); // all accessible via the scope chain
  }
  level2();
}

level1();

Best practices

  • Keep variables scoped as narrowly as possible - declare them inside the block or function where they are actually used
  • Avoid polluting the global scope - wrap code in functions or modules rather than declaring everything globally
  • Use let/const for predictable block scoping instead of var's looser function scoping
  • Understand the scope chain when debugging "variable is not defined" errors - the variable may simply be out of reach from where you are trying to access it

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation