Skip to content
Codewilds

Lesson 11 of 34 · Functions

JavaScript Scope and Closures

medium20 XP3 min read

Where can a variable be used? And what happens to a function's variables after the function has finished running? The answers are scope and closures, two ideas that sound academic but power everyday JavaScript: event handlers, React hooks, private state and much more.

Closures are also a favourite JavaScript interview topic. After this lesson, you'll be ready for it.

Scope: where variables live

Scope is the region of code where a variable is visible.

  • A variable declared outside any function or block is in the global scope and visible everywhere.
  • A variable declared inside a function exists only inside that function.
  • let and const are also block-scoped: a variable declared inside { } (an if, a loop) exists only inside those braces.
const realm = "Scriptoria"; // global

function enterTavern() {
  const drink = "cider";    // function scope
  if (realm === "Scriptoria") {
    const song = "ballad";  // block scope
    console.log(drink, song); // cider ballad
  }
  // console.log(song); // ReferenceError: song is not defined
}

enterTavern();
// console.log(drink); // ReferenceError: drink is not defined

Inner code can see outer variables, but outer code can't see inner ones. Scopes nest like boxes inside boxes, and JavaScript looks for a name from the innermost box outward. This is called lexical scope: what a function can see depends on where it's written in the code.

Shadowing

If an inner scope declares a variable with the same name as an outer one, the inner one shadows (hides) the outer one inside that scope:

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

Closures: functions that remember

Functions can create and return other functions. Here's the surprising part: the inner function keeps access to the outer function's variables, even after the outer function has returned.

function makeGreeter(greeting) {
  return (name) => `${greeting}, ${name}!`;
}

const hello = makeGreeter("Hello");
const ahoy = makeGreeter("Ahoy");

console.log(hello("Ada"));  // Hello, Ada!
console.log(ahoy("Linus")); // Ahoy, Linus!

makeGreeter finished running long ago, yet hello still remembers greeting. A function bundled together with the variables it remembers is called a closure.

Private state with closures

Closures can also remember variables that change. This is how you create state that nobody else can touch:

function makeWallet() {
  let gold = 0; // private: only the returned function can reach it
  return (amount) => {
    gold += amount;
    return gold;
  };
}

const wallet = makeWallet();
console.log(wallet(10)); // 10
console.log(wallet(5));  // 15

There's no way to change gold from outside except by calling wallet. Each call to makeWallet() creates a fresh, independent gold variable:

const other = makeWallet();
console.log(other(1)); // 1 (it doesn't share gold with wallet)

Common mistakes

  • Expecting outer code to see inner variables. A variable declared inside a function or block disappears outside it.
  • Putting the state in the wrong place. If let count = 0 lives inside the returned function, it resets to 0 on every call. It must live in the outer function.
  • Accidentally sharing state. A variable declared at the top level is shared by everyone. Create it inside a factory function to give each caller its own copy.

Assignment

Write two "factory" functions that return new functions:

  1. makeCounter() returns a function. Each time you call that returned function, it returns the next number, starting at 1. Every counter is independent.

    const counter = makeCounter();
    counter(); // 1
    counter(); // 2
    counter(); // 3
  2. makeMultiplier(factor) returns a function that takes a number n and returns n * factor.

    const triple = makeMultiplier(3);
    triple(5); // 15

Premium lesson

Unlock the full Learn JavaScript course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Scope and closures in other languages

Need a quick reminder? The JavaScript cheat sheet has every topic of Learn JavaScript on one page.

Lesson last updated on .

Write code ↓
JavaScript+20 XP

Lesson 11 is part of the full course. The first 8 lessons are free.

Premium lesson

Unlock the full Learn JavaScript course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.