#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
JavaScript Fundamentals

Function closures

A closure is a function bundled together with the variables from the place where it was created. Even after the outer function has finished running, the inner function can still read and update those variables. Closures are not a special syntax you have to type; they happen automatically whenever a function uses a variable from an enclosing scope. They power private state, function factories, event handlers that remember values, and much of how React hooks behave.

Watching a closure keep a variable alive

function createCounter(start = 0) {
  let count = start;            // not reachable from outside

  return {
    increment() { count += 1; return count; },
    reset() { count = start; return count; }
  };
}

const visits = createCounter();
visits.increment(); // 1
visits.increment(); // 2

const other = createCounter(10);
other.increment();  // 11
visits.increment(); // 3, each counter has its own count

console.log(visits.count); // undefined

Normally, local variables disappear when a function returns. Here, the two methods still refer to count, so JavaScript keeps it alive. Each call to createCounter creates a fresh count, which is why the two counters do not interfere.

Closures as private data

Nothing outside createCounter can touch count directly. The only way to change it is through the methods you chose to expose. This "module pattern" was the main way to hide implementation details before classes gained private #fields, and it is still handy for small utilities.

Function factories

A function that returns a customised function is called a factory. The returned function closes over the arguments given to the factory.

function makeDiscount(percent) {
  return price => price - (price * percent) / 100;
}

const festivalSale = makeDiscount(20);
const clearance = makeDiscount(50);

festivalSale(1000); // 800
clearance(1000);    // 500

The same idea appears in event handling: a click handler created inside a loop or a component remembers the item it was created for.

The loop pitfall with var

A famous surprise happens when closures are created in a loop that uses var. Because var is function-scoped, every closure shares one variable, and by the time the callbacks run, the loop has finished.

In for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100); } the output is 3, 3, 3. Switching to let gives each iteration its own binding, so you get 0, 1, 2. This is one of the strongest reasons to avoid var in modern code.

Closures capture variables, not values

A closure holds a live link to the variable, not a snapshot of its value at creation time. If the variable changes later, the closure sees the new value. In React, the reverse problem shows up as a "stale closure": a callback created during one render keeps seeing that render's state. Understanding closures explains why the functional update form setCount(c => c + 1) fixes it.

Because closures keep variables alive, a closure attached to a long-lived object, such as a global event listener, also keeps everything it references in memory. Remove listeners you no longer need.

Debouncing a search box is a practical example that combines these ideas: a function remembers a timer ID in a closure and resets it on every keystroke.

Summary points

  • Inner functions remember variables from where they were defined.
  • Each call to the outer function creates a separate set of variables.
  • Use let in loops so each closure gets its own value.

Ready to master real-world web development?

Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.

Explore Course