Mind~G
Javascript

Closure

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

Closure: Function + Remembering the variables from its outer function.

Use Case

  1. To make private variables.

  2. To keep data safe from being changed from outside.

Example

function outerFunction() {
  let count = 0; // this variable lives inside outerFunction
 
  function innerFunction() {
    count = count + 1;
    console.log(count);
  }
 
  return innerFunction;
}
 
const counter = outerFunction();
counter(); // prints 1
counter(); // prints 2
counter(); // prints 3

How It Works

  1. When outerFunction runs it creates a variable called count.

  2. Then it creates another function inside it called innerFunction.

  3. Then it returns innerFunction.

  4. When we call outerFunction we get innerFunction back and store it in counter.

  5. Even though outerFunction has finished running the innerFunction still remembers count.

  6. So every time we call counter(), it can still use and change count.

Difference Between Closure and Scope

  • Scope means where a variable is available.
  • Closure means when a function keeps using variables from another scope even after that scope is gone.

Important Points

  1. Closure always remembers variable, not just value.

  2. Each function call creates a new closure with its own memory.

  3. var is function scoped, not block scoped.

    In loops with var, all closures share the same variable. That is why setTimeout with var often prints the same number.

  4. let and const are block scoped.

    In loops with let, every iteration gets a new variable. That is why setTimeout with let prints 0, 1, 2 correctly.

  5. If two variables point to the same closure, they share the same memory.

    const a = test();
    const b = a;

    Both a and b use the same closure, so they share data.

  6. Closures can keep variables alive even after the outer function is finished.

  7. Understand scope chain.

    If a variable is not found inside a function, JavaScript looks one level outside, then another, and so on, until it finds it. That chain is what makes closure possible.

On this page