← JavaScript

Basic · 4 of 12 · 16 min read

Scope and the scope chain

Where a name is visible, how the engine looks one up, and why let in a loop behaves differently from var.

  • Scope

Scope is the region of code where a name is visible. JavaScript decides it where the code is written, not where it runs — which is why you can work out every answer on this page by reading, without executing anything.

The three kinds

const globalName = 'global'; // module or global scope

function outer() {
  const functionName = 'function'; // function scope

  if (true) {
    const blockName = 'block';     // block scope — any { }
    console.log(globalName, functionName, blockName); // all three are visible
  }

  // console.log(blockName); // ReferenceError: blockName is not defined
}

outer();
// console.log(functionName); // ReferenceError

A block is any pair of braces: an if, a loop, a switch, or braces on their own. The exception is var, which ignores blocks entirely:

function f() {
  if (true) {
    var fromVar = 'var';
    let fromLet = 'let';
  }
  console.log(fromVar);   // "var" — `var` is scoped to the function
  // console.log(fromLet); // ReferenceError — `let` is scoped to the block
}
f();
var let const
Scope the function the block the block
Before its line undefined ReferenceError (TDZ) ReferenceError
Redeclare in the same scope allowed SyntaxError SyntaxError
Reassign yes yes no
Creates a property on window yes, at top level no no
Fresh binding per loop iteration no yes n/a

const prevents rebinding, not mutation:

const user = { name: 'Ana' };
user.name = 'Beto';     // fine — the object changed, the binding did not
console.log(user.name); // "Beto"
// user = {};           // TypeError: Assignment to constant variable

The scope chain

When a name is read, the engine checks the current scope, then the enclosing one, and keeps going until it finds the name or runs out:

const level1 = 'one';

function a() {
  const level2 = 'two';

  function b() {
    const level3 = 'three';
    console.log(level3, level2, level1); // found at 0, 1 and 2 steps out
    // console.log(level4);               // ReferenceError — nothing left to search
  }

  b();
  // console.log(level3); // ReferenceError — the chain does not run inwards
}

a();
b  →  a  →  module  →  global  →  (not found: ReferenceError)

Lexical, not dynamic: the chain follows where the function was written, not who called it.

const value = 'outer';

function reader() {
  console.log(value); // always "outer"
}

function caller() {
  const value = 'inner'; // a different variable entirely
  reader();              // "outer" — reader's chain goes through where it was written
}

caller();

That is the single most important property of scope in JavaScript, and it is what makes closures predictable.

Shadowing

An inner declaration with the same name hides the outer one for that whole block:

const name = 'outer';

function show() {
  const name = 'inner';
  console.log(name); // "inner"
}

show();
console.log(name); // "outer" — untouched

The trap is that the inner binding exists from the opening brace, so you cannot read the outer one first:

let count = 1;
{
  // console.log(count); // ReferenceError: Cannot access 'count' before initialization
  let count = 2;
  console.log(count);    // 2
}

With var there is no shadow at all, which is the sloppiness block scoping fixed:

var n = 1;
{
  var n = 2; // the same variable
}
console.log(n); // 2

The loop difference

The question that comes up most. let creates a new binding for every iteration; var does not.

const withVar = [];
for (var i = 0; i < 3; i++) withVar.push(() => i);
console.log(withVar.map((f) => f())); // [3, 3, 3] — one `i`, and it ended at 3

const withLet = [];
for (let j = 0; j < 3; j++) withLet.push(() => j);
console.log(withLet.map((f) => f())); // [0, 1, 2] — three separate `j`s

The same bug with a timer, which is how it usually appears in real code:

for (var k = 0; k < 3; k++) setTimeout(() => console.log('var', k), 0);  // 3 3 3
for (let m = 0; m < 3; m++) setTimeout(() => console.log('let', m), 0);  // 0 1 2

Before let, the fix was an IIFE that captured a copy per iteration:

for (var p = 0; p < 3; p++) {
  (function (copy) {
    setTimeout(() => console.log('iife', copy), 0); // 0 1 2
  })(p);
}

Worth knowing because you will read it, not because you should write it.

Accidental globals

An assignment to a name that was never declared creates a global — in sloppy mode, silently:

function setup() {
  conut = 0; // a typo for `count`
}
setup();
console.log(typeof conut); // "number" — it leaked to the global object

Strict mode, which every ES module is, turns that into an error:

'use strict';
function setup() {
  // conut = 0; // ReferenceError: conut is not defined
}

And at the top level of a classic script, var and function declarations become properties of window while let and const do not:

// In a plain <script>:
var a = 1;
let b = 2;
// console.log(window.a, window.b); // 1 undefined

In a module, none of them do — which is one more reason modules are the default.

Scope is what makes a closure

A function keeps the scope chain it was created with, even after the outer call has returned:

function makeCounter() {
  let count = 0;             // lives in makeCounter's scope

  return function () {
    count += 1;              // still reachable through the chain
    return count;
  };
}

const next = makeCounter();
console.log(next(), next()); // 1 2 — the scope outlived the call

Each call to makeCounter creates a separate scope, so counters do not share state:

const a = makeCounter();
const b = makeCounter();
console.log(a(), a(), b()); // 1 2 1

The closures page goes further; scope is the mechanism underneath it.

Common mistakes

Expecting a block to contain a var

Mistake. if (x) { var result = compute(); } and then checking result outside, assuming it is scoped. Why it fails. var is function-scoped, so the name exists either way — as undefined when the branch did not run, which is a different bug from a ReferenceError. What to do instead. let, declared where you want it visible. Default to const.

Reading an outer variable in a block that shadows it

Mistake. let x = 1; { console.log(x); let x = 2; } Why it fails. The inner x shadows from the opening brace, so the read lands in the Temporal Dead Zone. What to do instead. Rename one of them. Same-name shadowing is rarely worth the confusion.

Assuming const means immutable

Mistake. const config = { debug: false } and treating it as unchangeable. Why it fails. const freezes the binding, not the value: the object’s properties are still writable. What to do instead. Object.freeze when you need the value protected, and remember that is only one level deep.

Check yourself

3 questions from the bank on what you just read. Answering here does not affect your quiz history.

const protects something specific, and it is worth knowing exactly what.

What does this log?

Code sample
const user = { name: "Ana" };
user.name = "Beto";
console.log(user.name);

What is the scope chain?

let and var differ in several ways. Which one causes the most real bugs?

Practise Scope →

Further reading

Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.

Reaching the end of a lecture marks it as read.