Curriculum / Intermediate / Lesson 14

Closures

What they are, why they matter, and how to spot them.

14 of 30
intermediate 📖 7 min read 🎯 4 questions

What is a Closure?

A closure is a function that "remembers" its lexical scope even when the function is executed outside that scope. In simpler terms: a closure gives you access to an outer function's scope from an inner function.

💡 Key insight Every function in JavaScript is a closure. Functions remember the variables from where they were created, not where they're called.

Basic Closure Example

function outer() {
  let message = "Hello from outer!";
  
  function inner() {
    console.log(message); // inner remembers 'message'
  }
  
  return inner;
}

let fn = outer();
fn(); // "Hello from outer!"

Practical Use Cases

Private Variables with Closures

function createCounter() {
  let count = 0; // private variable
  
  return {
    increment: function() { count++; },
    decrement: function() { count--; },
    getCount: function() { return count; }
  };
}

let counter = createCounter();
counter.increment();
counter.increment();
console.log(counter.getCount()); // 2
// counter.count is not accessible

Common Mistakes

Quick Quiz

1. What is a closure?

2. Which is a use case for closures?

3. What does a function factory do?

Summary

Back to curriculum