Closures | Dataplexa

Closures

Closures are one of the most powerful and sometimes confusing concepts in JavaScript.

Once you understand closures, many advanced JavaScript patterns will suddenly make sense.


What Is a Closure?

A closure is created when a function remembers variables from its outer scope even after the outer function has finished executing.

In simple words:

  • A function keeps access to variables
  • Those variables were defined outside the function
  • The outer function has already returned

A Simple Example


function outer() {
  let count = 0;

  function inner() {
    count++;
    return count;
  }

  return inner;
}

const counter = outer();
console.log(counter());
console.log(counter());
  

Even though outer() has finished running, the inner function still remembers count.


Why Does This Happen?

JavaScript does not destroy variables that are still being used by inner functions.

The inner function forms a closure around the variables it needs.

This behavior is intentional and very useful.


Real-World Analogy

Think of a closure like a backpack.

  • The function carries variables with it
  • Those variables stay available wherever the function goes

That backpack is the closure.


Practical Use Case

Closures are commonly used to:

  • Create private variables
  • Maintain state
  • Control access to data

function createUser(name) {
  let score = 0;

  return {
    increaseScore() {
      score++;
      return score;
    },
    getName() {
      return name;
    }
  };
}

const user = createUser("Alex");
user.increaseScore();
  

Closures and Loops (Common Pitfall)

Closures behave differently depending on how variables are declared.


for (var i = 0; i < 3; i++) {
  setTimeout(() => {
    console.log(i);
  }, 1000);
}
  

This prints 3, 3, 3 because var does not create block scope.

Using let fixes this:


for (let i = 0; i < 3; i++) {
  setTimeout(() => {
    console.log(i);
  }, 1000);
}
  

Why Closures Matter

Closures are used in:

  • Event handlers
  • Callbacks
  • Async programming
  • Framework internals

Understanding closures makes you a stronger JavaScript developer.


Common Beginner Mistakes

  • Thinking closures copy values
  • Forgetting how scope works
  • Misusing var inside loops

Closures reference variables, not values.


Thumb Rules

  • A closure remembers its outer variables
  • Functions carry their scope with them
  • Closures are created automatically
  • Use let and const to avoid surprises

What Comes Next?

Now that you understand closures, the next step is learning how functions communicate asynchronously using callbacks.

In the next lesson, we will explore callbacks.