Skip to content
Shubham JangleResources
JavaScript

Explore topics

What is closure

Watch the walkthrough
Open on Instagram

Revision clarifications

Closures retain access to bindings, not frozen copies of values. Two calls to createCounter create independent environments; repeated calls to one returned function share its count. Captured DOM nodes can remain reachable while the closure is retained.

The source notes below are copied unchanged apart from line endings. Examples are independent; some deliberately throw or depend on browser markup.

Original HackTheCode notes

Read the original Markdown

A closure is combination of function and it's lexical environment in which function was created.

// Closures
function outerFunction() {
  let outerVariable = "I'm outside!";

  function innerFunction() {
    console.log(outerVariable);
  }

  return innerFunction;
}

const myInnerFunction = outerFunction();
myInnerFunction(); // Output: "I'm outside!"
// Example 1: Having Private variables
function createCounter() {
  let count = 0;

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

const counter = createCounter();

console.log(counter()); // Output: 1
console.log(counter()); // Output: 2
console.log(counter()); // Output: 3
// Example 2: With event listeners
function setupButton() {
  let clickCount = 0;

  document.getElementById("myButton").addEventListener("click", function () {
    clickCount++;
    console.log(`Button clicked ${clickCount} times`);
  });
}

setupButton();