JavaScript Tutorial · Functions · Lesson 21 of 44

JavaScript Scope and Closures

Block scope, function scope and how closures remember variables.

Scope

Scope decides where a variable is visible.

  • Variables declared with let/const inside { } are block-scoped.
  • Variables declared inside a function are visible only inside that function.
  • Inner code can read variables from outer scopes, but not the other way round.
Example 1Try it yourself
const site = "ReadyCamel";        // global scope
function show() {
  const page = "Scope";         // function scope
  if (true) {
    const note = "block only";  // block scope
    console.log(site, page, note);
  }
  console.log(typeof note);
}
show();
console.log(typeof page);

Output

ReadyCamel Scope block only
undefined
undefined

Closures

A closure is a function that remembers the variables from where it was created — even after that outer function has returned. Closures are how JavaScript gives you private state:

Example 2Try it yourself
function makeCounter() {
  let count = 0;  // private: only the returned functions can see it
  return {
    increment: () => ++count,
    current: () => count,
  };
}
const a = makeCounter();
const b = makeCounter();
a.increment();
a.increment();
b.increment();
console.log(a.current(), b.current());

Output

2 1

Closures in practice

Function factories, event handlers and debouncing all use closures:

Example 3Try it yourself
function multiplier(factor) {
  return (n) => n * factor;
}
const double = multiplier(2);
const triple = multiplier(3);
console.log(double(10), triple(10));

Output

20 30

Closures and loops are a favourite interview question — try var vs let in closures.

Test yourself

What is a closure?

  1. A function with no parameters
  2. A function that remembers variables from the scope where it was created
  3. A way to close a browser window
  4. A function that has finished running
Show answer

Answer: A function that remembers variables from the scope where it was created

Practice next