ā¤ Like
šŸ”– Save
šŸ”— Share
@thedevspaceio
@thedevspaceio

JavaScript Closure Cheatsheet

@thedevspaceio

šŸ”’ JavaScript Closure Cheatsheet

A closure is a function that remembers the environment where it was created, enabling private state and powerful factory patterns.

āœ… What is a closure? āœ… How closure works āœ… Why closure āœ… Real-world applications āœ… Memory considerations

#javascript #closure #scope #functions #webdev #frontend #developer tools #coding #tips


What is a closure?

A closure is a function that remembers the environment in which it was created, even when that function is executed outside that scope.

Consider this function:

js
function outer() {
  let count = 0;
 
  function inner() {
    count += 1;
    console.log(count);
  }
 
  return inner;
}
 
const counter = outer();
counter(); // 1
counter(); // 2
counter(); // 3

How closure works

closure


Why closure

Data privacy: Keep variables hidden from the global scope.

js
function createCounter() {
  let count = 0;
 
  return {
    increment() {
      count += 1;
      return count;
    },
  };
}
 
const counter = createCounter();
 
console.log(counter.increment()); // 1
console.log(counter.count); // undefined

State preservation: Maintain state between function calls without using global variables.

js
function createCounter(start = 0) {
  let count = start;
 
  return {
    increment() {
      count += 1;
      return count;
    },
  };
}
 
const counterA = createCounter(10);
 
console.log(counterA.increment()); // 11
console.log(counterA.increment()); // 12
 
const counterB = createCounter(0);
 
console.log(counterB.increment()); // 1

Real-world applications

Module pattern

Closures let you create modules with public and private members.

js
const bankAccount = (function () {
  let balance = 0;
 
  return {
    deposit(amount) {
      balance += amount;
      return balance;
    },
    withdraw(amount) {
      balance -= amount;
      return balance;
    },
    getBalance() {
      return balance;
    },
  };
})();
 
bankAccount.deposit(100);
console.log(bankAccount.getBalance()); // 100

Event handlers

Closures preserve data for callbacks and event listeners.

js
function setupButton(buttonId, message) {
  const button = document.getElementById(buttonId);
 
  button.addEventListener("click", () => {
    console.log(message);
  });
}
 
setupButton("save", "Saved!");
setupButton("delete", "Deleted!");

Function factories

Create functions configured with specific values.

js
function makeMultiplier(factor) {
  return function (number) {
    return number * factor;
  };
}
 
const double = makeMultiplier(2);
const triple = makeMultiplier(3);
 
console.log(double(5)); // 10
console.log(triple(5)); // 15

Memory considerations

Closures keep referenced variables alive. Be careful not to accidentally retain large objects.

js
function processBigData(data) {
  const huge = data; // retained by closure
 
  return function getSummary() {
    return huge.length;
  };
}
 
const summary = processBigData(largeArray);
// `largeArray` stays in memory as long as `summary` exists

Release closures when they are no longer needed to avoid memory leaks.

Full-Stack AI Developer Roadmap

From HTML & CSS to working with AI models, all in one structured roadmap.

@thedevspaceio
www.thedevspace.io