AI Hints
Home›JavaScript Tutorial›Arrow Functions and Scope
JavaScript · Lesson 36 of 138

Closures

Functions that remember.

⏱ 2 min read▶ Video at 43:33🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Here's one of JavaScript's most powerful ideas. A function made inside another function remembers the variables around it, even after the outer function has finished. That memory is called a closure.

Closures
From the video: Closures
  • A function inside a function
  • It remembers its surroundings
  • A closure

A counter

Make counter creates a count variable, and returns a little arrow function that adds one to it. Each time we call make counter, we get a brand new count. Run it. Counter A and counter B each remember their own count, and nothing else can touch it.

app.jsjavascript
function makeCounter() {
  let count = 0;
  return () => {
    count++;
    return count;
  };
}

const counterA = makeCounter();
const counterB = makeCounter();
console.log(counterA(), counterA(), counterA());
console.log(counterB());
Output
1 2 3
1

Where closures appear

Closures are everywhere in JavaScript, often without you noticing. Event handlers in web pages remember variables from where they were created. Timers do too. And closures are a neat way to keep data private, like the count, which nothing outside can change directly.

keyvalue
Closurea function plus its memory
Remembersouter variables
Each calla fresh memory
Used inevents, timers, privacy

Summary

A closure is a function that remembers the variables from where it was made. Next, passing functions to other functions, with callbacks.

Key takeaways
  • Inner function remembers
  • Private state
  • Each call is separate
Next up: Callbacks — functions as values