0
0
JavascriptHow-ToBeginner · 3 min read

How Do Closures Work in JavaScript: Simple Explanation and Examples

In JavaScript, a closure is a function that remembers and can access variables from its outer (enclosing) function even after that outer function has finished running. This happens because functions keep a reference to their lexical environment, allowing them to use variables defined outside their own scope.
📐

Syntax

A closure is created when a function is defined inside another function and the inner function accesses variables from the outer function.

  • outerFunction(): The function that creates variables.
  • innerFunction(): The function that uses variables from outerFunction.
  • return innerFunction: Returns the inner function so it can be called later, keeping access to outer variables.
javascript
function outerFunction() {
  let outerVariable = 'I am outside!';
  function innerFunction() {
    console.log(outerVariable);
  }
  return innerFunction;
}
💻

Example

This example shows how a closure keeps access to the outerVariable even after outerFunction has finished running.

javascript
function outerFunction() {
  let outerVariable = 'I am outside!';
  function innerFunction() {
    console.log(outerVariable);
  }
  return innerFunction;
}

const myClosure = outerFunction();
myClosure();
Output
I am outside!
⚠️

Common Pitfalls

One common mistake is expecting closures to capture the current value of a variable inside a loop, but they actually capture the variable itself, which can lead to unexpected results.

Another pitfall is creating closures that hold onto large objects or data, which can cause memory leaks if not handled carefully.

javascript
function createFunctions() {
  let funcs = [];
  for (let i = 0; i < 3; i++) {
    funcs.push(function() {
      console.log(i);
    });
  }
  return funcs;
}

const functions = createFunctions();
functions[0](); // 0
functions[1](); // 1
functions[2](); // 2
Output
0 1 2
📊

Quick Reference

  • A closure is a function with access to its own scope, the outer function’s scope, and the global scope.
  • Closures allow data to be private and persistent between function calls.
  • Use let or const in loops to avoid common closure pitfalls.

Key Takeaways

Closures let functions remember variables from their outer scope even after that scope ends.
Closures are useful for creating private variables and functions.
Use let or const in loops to avoid unexpected closure behavior.
Closures can cause memory leaks if they hold onto large data unnecessarily.
Understanding closures helps you write cleaner and more powerful JavaScript code.