Sitemap
JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Javascript Closures

1 min readNov 22, 2025

--

A closure allows a function to access variables that were defined outside of it. The closure is created when an inner function captures variables from its outer scope. It makes variables accessible even after outer function has executed. It works due to lexical scoping:

Lexical Scoping:

JavaScript looks at where a function is defined, not where it is executed. Inner functions always have access to variables of:

  1. Their own scope
  2. Outer function Scope
  3. The global scope

Example:

function makeCounter() {
let count = 0;

return function () {
count++;
console.log(count);
};
}

const doIncrement = makeCounter();
doIncrement(); // 1
doIncrement(); // 2
doIncrement(); // 3

In this example, the variable count is defined inside the outer function makeCounter(). The function returns an inner function that increments this count. Because the inner function is created inside the outer function, it can access the count variable from the outer function’s scope.

Get Tech Mentor’s stories in your inbox

Join Medium for free to get updates from this writer.

A lexical scope is created for the inner function, and that scope contains the count variable. This is why the returned function can still access and update count.

So, when we call doIncrement(), it continues to update the count variable preserved in its lexical scope.
This behaviour is known as a closure.

When to use Closures:

  1. Data Privacy: keep variables private and inaccessible from the global scope
  2. Callbacks: to call callback functions from the function
  3. To maintain state across multiple function calls
  4. Caching: Store results of expensive computations for reuse.

--

--

Tech Mentor
Tech Mentor

Written by Tech Mentor

Turning technology concepts into clear writing. Writing about systems design, JavaScript, Java, and web technologies.

JavaScript in Plain English
JavaScript in Plain English

Published in JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.