DEV Community

Cover image for What is Closure in JavaScript? Explained with Real-World Examples
WebTechnology Tutorials
WebTechnology Tutorials

Posted on • Edited on • Originally published at webcodingwithankur.blogspot.com

What is Closure in JavaScript? Explained with Real-World Examples

What is CLosure in JavaScriptπŸ” What is Closure in JavaScript?

In JavaScript, a closure is created when a function "remembers" variables from its outer lexical scope, even after the outer function has returned.

Closures enable inner functions to continue accessing variables from the outer function. This powerful concept is key to writing flexible and secure code.


Example of a Closure

function outerFunction() {
  let outerVariable = "Hello from the outer scope";

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

  return innerFunction;
}

const myClosure = outerFunction();
myClosure(); // Output: Hello from the outer scope

Enter fullscreen mode Exit fullscreen mode

How it works:

  • outerFunctiondefines a local variable outerVariable.
  • innerFunctionis declared inside outerFunction and uses outerVariable.
  • When outerFunction() is called, it returns innerFunction.
  • Even though outerFunction() has completed, the returned innerFunction still has access to outerVariable.

This behavior is what we call a closure.


Why Use Closures?

Closures are useful when:

  • You want to keep certain data private.
  • You need to preserve a value between function calls.
  • You work with asynchronous functions like setTimeout, setInterval, or API calls.

Real-World Example: Counter

function createCounter() {
  let count = 0;

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

const counter1 = createCounter();
counter1(); // 1
counter1(); // 2

const counter2 = createCounter();
counter2(); // 1

Enter fullscreen mode Exit fullscreen mode

Each counter instance has its own independent count value. This happens because each call to creates a new closure.


Summary

A closure is a function bundled with its lexical environment. It gives you the ability to:

  • Maintain state across executions
  • Hide and protect variables
  • Work more efficiently with asynchronous or functional code

Closures are a core concept in JavaScript and are commonly used in practical applications like module patterns, callbacks, currying, and event handlers.


Read More

To see the original version of this blog with additional formatting and examples, visit:
https://webcodingwithankur.blogspot.com/2025/06/what-is-closure-in-javascript.html.html

Top comments (0)