Skip to content
jshacks.dev
Fundamentals

Lexical Scope and the Scope Chain in JavaScript Explained

Lexical scope means a function sees the variables from where it was written, not where it is called. See the scope chain, closures and why this differs.

6 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, TypeScript, Vite and npm logos.

A function defined in one place and called from another uses the variables of the place it was written. That sentence is lexical scope, and the opposite rule, used by some older languages, looks up variables from the caller. The lexical rule is what makes JavaScript code predictable to read: you can answer "where does this name come from" by looking at the surrounding text, without tracing every call. This post shows the rule with output on Node.js 24, describes the scope chain the engine walks, explains how closures fall out of it and marks the one thing in JavaScript that is not lexical. It builds on block versus function scope and is the foundation of the guide to scope, hoisting and closures.

Where a function is written decides what it sees

Here a function reads a variable named owner. Two scopes define that name, and the call site is inside one of them.

JavaScript
const owner = "module";

function showOwner() {
  return owner;
}

function callFromElsewhere() {
  const owner = "caller";
  return showOwner();
}

console.log(showOwner());
console.log(callFromElsewhere());
Text
module
module

Both calls print module. The function showOwner was written at module level, so its owner is the module-level one, and the local owner inside callFromElsewhere is invisible to it. Under dynamic scope the second call would print caller. Some shell languages and old Lisps work that way, and JavaScript does not.

The consequence for debugging is helpful: to find where a variable in a function comes from, read outward through the enclosing text. You never need the stack.

The scope chain

Every scope has a link to the scope that encloses it. Looking up a name starts at the innermost scope and follows the links outward until the name is found or the global scope is exhausted.

JavaScript
const a = "module a";
const b = "module b";

function outer() {
  const b = "outer b";
  const c = "outer c";

  function inner() {
    const c = "inner c";
    return [a, b, c];
  }

  return inner();
}

console.log(outer());
Text
[ 'module a', 'outer b', 'inner c' ]

For a, the lookup checks inner, then outer, then the module, and finds it there. For b, it finds the declaration in outer first, which shadows the module's. For c, the innermost match wins. The order of that walk is the chain: inner, outer, module, global. A name found nowhere throws a ReferenceError when read.

The chain is fixed when the code is written. The engine builds it from the nesting of the source, and that is why the term "lexical" is used: it refers to the lexical structure of the text.

Callbacks use their own chain

Timers, promise callbacks and event handlers run later and from other places, and none of that changes the scope they see.

JavaScript
const tag = "defined at module level";

function schedule() {
  const tag = "inside schedule";
  setTimeout(function () {
    console.log(tag);
  }, 0);
  setTimeout(show, 0);
}

function show() {
  console.log(tag);
}

schedule();
Text
inside schedule
defined at module level

The anonymous callback was written inside schedule, so it sees the local tag. The function show was written at module level, so it sees the module's, even though both were scheduled from the same place. Where a function is passed does not matter. This property lets you hand a function to a library and trust that its variables mean what they meant when you wrote it.

A closure is a function plus its chain

When a function outlives the call that created it, it keeps the scope chain alive. That combination is a closure, and no special syntax is involved.

JavaScript
function makeCounter(start) {
  let count = start;

  return {
    next() {
      count += 1;
      return count;
    },
    peek() {
      return count;
    },
  };
}

const first = makeCounter(0);
const second = makeCounter(100);

first.next();
first.next();
second.next();

console.log(first.peek(), second.peek());
console.log(typeof count);
Text
2 101
undefined

Each call to makeCounter creates a new count, and the two methods returned for it share that one variable. The two counters do not interfere, because each has its own chain. The variable count is not reachable from outside, since no name in the outer scopes refers to it, so the only way to touch it is through the returned methods. That is the standard way to hide state in JavaScript, and it follows from the lexical rule, not from any extra feature.

The price is memory: a closure keeps every variable in its chain alive, even ones it never reads, in engines that do not trim them. A callback that captures a large array it does not need can keep the array alive for as long as the callback exists. The post on garbage collection covers how to spot that.

What is not lexical: this

The word "lexical" is the reason JavaScript has two kinds of function and one confusing keyword. For ordinary functions, this is decided by how the function is called, which is dynamic. For arrow functions, this comes from the enclosing scope, which is lexical.

JavaScript
const report = {
  name: "weekly",
  regular() {
    return [1, 2].map(function () {
      return this === undefined ? "lost" : this.name;
    });
  },
  arrow() {
    return [1, 2].map(() => this.name);
  },
};

console.log(report.regular());
console.log(report.arrow());
Text
[ 'lost', 'lost' ]
[ 'weekly', 'weekly' ]

The ordinary function inside map is called without a receiver, so in strict mode its this is undefined. The arrow function has no this of its own, so it uses the this of the arrow method that contains it. That difference is the main reason arrow functions were added, and it is why a callback inside a method is usually written as an arrow. The post on the this keyword lists the call patterns that set it.

The same split applies to arguments: an ordinary function has its own, an arrow function uses the enclosing function's. Rest parameters are the portable alternative.

Lookups that cannot be resolved ahead of time

Two older features break the promise that scope is readable from the text. with adds an object's properties to the scope chain at runtime, and eval can declare variables in the surrounding scope. Both are disallowed or restricted in strict mode and inside modules, which is the main reason modern code can rely on the lexical rule.

JavaScript
function direct() {
  const secret = "local";
  return eval("secret");
}

function indirect() {
  const secret = "local";
  return (0, eval)("typeof secret");
}

console.log(direct());
console.log(indirect());
Text
local
undefined

A direct eval sees the local scope, and an indirect call, written with the comma trick, runs in the global scope and cannot see secret. Neither is a pattern to use. They matter because the presence of eval forces an engine to treat names in that function as dynamic, which defeats the static resolution that makes lexical scope fast. Linters ban both.

A short way to trace a name

When you need to know where a name comes from, apply four steps. Find the function or block that contains the use. Look for a declaration with that name in it, including parameters. If none, move to the enclosing scope and repeat, until you reach the module. And remember that the closest match wins. You can do this by reading, without running anything, which is the benefit the design buys.

In the browser, the Sources panel in DevTools shows a "Scope" pane at a breakpoint, listing the local, closure and global scopes in chain order, and Node's inspector shows the same. Seeing a real chain once makes the model concrete.

Where the lexical model needs care

Three situations deserve attention. Closures inside loops share a binding when the loop uses var, as shown in the post on var, let and const. Long-lived closures can retain large objects. And module cycles can read a binding before it is initialized, which the post on the temporal dead zone explains.

None of these is a reason to avoid closures. They are the tool that makes callbacks, private state, partial application and most functional patterns work, and the lexical rule keeps them understandable.

The rule is defined in the specification under environment records and lexical environments, and MDN's closures guide walks through lexical scoping with more examples.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.