When you start learning JavaScript, functions look very simple. You create a function, pass some values, and return a result. However, as you go deeper, you discover something powerful called closure in JavaScript.

    At first, closures topic in JS may look confusing. However, once you understand the idea clearly, you will realize they are actually simple and extremely useful. Therefore, in this article, we will break everything down in very easy words with practical examples.

    What is a Closure in JavaScript?

    In simple words, a closure happens when a function in JavaScript remembers the variables from its outer function, even after the outer function has finished running.

    This might sound technical. So let’s understand it step by step.

    Normally, when a function finishes executing, its local variables are removed from memory. However, in some cases, JavaScript keeps those variables alive. This happens when an inner function still needs access to them. Because of this behavior, we get what is called a closure.

    So, a closure is created when:

    • A function is defined inside another function.
    • The inner function uses variables from the outer function.

    As a result, the inner function “closes over” those variables. That’s why it is called a closure.

    First Simple Example of Closure

    Let’s look at a basic example.

    function outerFunction() {
      let message = "Hello from outer function";
    
      function innerFunction() {
        console.log(message);
      }
    
      return innerFunction;
    }
    
    const myFunction = outerFunction();
    myFunction();

    Now let’s understand what is happening.

    First, outerFunction() runs. Inside it, we create a variable called message. Then we define innerFunction(), which uses that variable. After that, we return innerFunction.

    Normally, when outerFunction() finishes, its variables should disappear. However, since innerFunction still needs message, JavaScript keeps it in memory.

    Therefore, when we call myFunction(), it still remembers the value of message.

    That memory connection is a closure.

    Why Does Closure Happen?

    Closure happens because of something called lexical scope. In JavaScript, functions can access variables defined in their outer scope.

    In simple terms, inner functions can “see” variables of outer functions. However, the interesting part is that they can remember those variables even after the outer function has finished.

    Because of this feature, closures make JavaScript very powerful. Without closures, many advanced patterns would not be possible.

    Example 2: Creating a Counter Using Closure

    Now let’s see a more practical example.

    function createCounter() {
      let count = 0;
    
      return function() {
        count++;
        return count;
      };
    }
    
    const counter = createCounter();
    
    console.log(counter());
    console.log(counter());
    console.log(counter());

    Output:

    Now let’s understand why this works.

    When createCounter() runs, it creates a variable count. Then it returns an inner function that increases count.

    Even after createCounter() finishes, the returned function still remembers count. Because of that, each time we call counter(), the value increases.

    If there were no closure, the counter would reset to 0 every time. However, because of closure in JavaScript, the variable stays private and preserved.

    This is a real-world use case. Many libraries use closures to create private variables.

    Closures Help Create Private Variables

    In JavaScript, we do not have traditional private variables inside functions. However, closures help us simulate privacy.

    For example:

    function createBankAccount(initialBalance) {
      let balance = initialBalance;
    
      return {
        deposit: function(amount) {
          balance += amount;
          return balance;
        },
        getBalance: function() {
          return balance;
        }
      };
    }
    
    const account = createBankAccount(1000);
    
    console.log(account.deposit(500));
    console.log(account.getBalance());

    Here, the variable balance cannot be accessed directly from outside. However, the inner functions can still use it.

    Because of closure, the balance stays protected inside the function. Therefore, no one can change it directly.

    This pattern is commonly used in real applications.

    Common Mistake with Closures (Important to Understand)

    Sometimes beginners face problems when using closures inside a for loop.

    For example:

    for (var i = 1; i <= 3; i++) {
      setTimeout(function() {
        console.log(i);
      }, 1000);
    }

    You might expect the output to be:

    However, the output will actually be:

    This happens because var does not create block scope. Therefore, all functions share the same i.

    To fix this, we can use let instead:

    for (let i = 1; i <= 3; i++) {
      setTimeout(function() {
        console.log(i);
      }, 1000);
    }

    Now it will correctly print:

    Because let creates block scope, each iteration gets its own copy of i.

    Understanding this behavior is very important when working with closures.

    Why Are Closures Important?

    Closures are important because they:

    • Help create private variables.
    • Preserve data between function calls.
    • Enable function factories.
    • Are used heavily in callbacks and event handlers.

    Moreover, many advanced JavaScript concepts like currying and module patterns depend on closures. Therefore, mastering closure in JavaScript will improve your overall understanding of the language.

    Final Thoughts

    At first, closures may seem complicated. However, when you break them down, they are simply functions remembering their outer variables.

    In simple words, if a function is created inside another function and it uses outer variables, a closure is formed.

    Once you understand this concept, many JavaScript patterns start making sense. Therefore, instead of memorizing the definition, try building small examples like counters and private variables.

    Read Also – 
    1- Hoisting in JavaScript
    2- JavaScript Arrow Function

    Share.

    Vijay Chauhan is a tech professional with over 9 years of hands-on experience in web development, app design, and digital content creation. He holds a Master’s degree in Computer Science. At SchoolUnzip, Vijay shares practical guides, tutorials, and insights to help readers stay ahead in the fast-changing world of technology.

    Leave A Reply