JavaScript Closures: Examples, and Benefits | Updated 2025

JavaScript Closure Example with Step-by-Step Explanation

CyberSecurity Framework and Implementation article ACTE

About author

Prabu (Web Developer )

Prabu is a JavaScript educator who specializes in functional programming and lexical scoping. He explains closures with clear examples, showing how inner functions retain access to outer variables. His content helps learners master closures for cleaner, more powerful JavaScript code.

Last updated on 24th Sep 2025| 11013

(5.0) | 32961 Ratings

Introduction to JavaScript Closure

Closures are one of the most important and sometimes confusing concepts in JavaScript. They are a fundamental building block of the language and play a critical role in writing modular, maintainable, and efficient code. At its core, a closure is the combination of a function and its surrounding lexical environment. This means that a closure allows a function to “remember” and access variables from the scope in which it was created, even after that scope has finished executing. To understand how such concepts integrate into broader development workflows, exploring Full Stack Developer Training reveals how mastering both frontend and backend logic including closures, scopes, and asynchronous behavior prepares developers to build dynamic, scalable web applications. Closures are everywhere in JavaScript: in callbacks, event handlers, modules, and even in seemingly simple function calls. While beginners often find closures mysterious, understanding them unlocks the door to mastering JavaScript, as they are essential for creating private variables, implementing factory functions, and handling asynchronous code elegantly.


To Earn Your Full Stack Taining Course Certification, Gain Insights From Leading Web Developer Experts And Advance Your Career With ACTE’s Full Stack Developer Training Today!


Scope in JavaScript

To fully understand closures, it’s essential to have a solid grasp of scope. Scope determines where variables and functions are accessible in your code. In JavaScript, there are primarily three types of scope: global scope, function scope, and block scope. Global scope refers to variables declared outside any function or block. These variables are accessible anywhere in the program, which makes them powerful but also risky, as they can be modified from any part of the code. Function scope is created when you define a function. Variables declared inside a function are only accessible within that function, protecting them from unwanted changes elsewhere. Before ES6, JavaScript had only function scope, but ES6 introduced block scope via let and const. Block scope applies to variables declared inside curly braces {}, such as in loops or conditionals, making them inaccessible outside that block. Closures take advantage of JavaScript’s scoping rules by allowing inner functions to reach out to the scope of their parent functions. This connection is possible because of JavaScript’s unique way of handling variable access through the lexical environment, which we will explore next.

    Subscribe To Contact Course Advisor

    Lexical Environment

    • The lexical environment is the mechanism that makes closures possible. In JavaScript, a lexical environment is essentially a data structure that holds variable bindings and determines how variable names are resolved in nested functions. Each time a function is created, a new lexical environment is formed, linking the function to the scope where it was declared not where it is executed. This is why closures are sometimes described as functions “carrying” their scope with them.
    • Think of the lexical environment as a chain of scopes, often referred to as the scope chain. When you try to access a variable inside a function, JavaScript first looks inside the function’s local scope. If it doesn’t find the variable there, it looks in the next outer scope, and continues until it reaches the global scope.
    • This process is purely based on the physical placement of the functions in the code, not on the order in which they are called. Understanding the lexical environment helps explain why closures retain access to variables from their parent scope even after the parent function finishes executing, the inner function’s lexical environment still has a reference to those variables.

    • Would You Like to Know More About Full Stack Developer Training Course? Sign Up For Our Full Stack Developer Training Course Now!


      Creating a Closure

      Creating a closure in JavaScript is straightforward. It typically involves defining a function inside another function and returning the inner function so that it can be called later. To understand how closures fit into broader development practices, exploring Full Stack Developer Training reveals how mastering JavaScript concepts like closures, scopes, and asynchronous behavior equips developers to build responsive, modular applications across both frontend and backend environments.

      • function outerFunction(outerVariable) {
      • return function innerFunction(innerVariable) {
      • console.log(`Outer: ${outerVariable}, Inner: ${innerVariable}`);
      • };
      • }
      • const closureExample = outerFunction(“Hello”);
      • closureExample(“World”); // Output: Outer: Hello, Inner: World

      Here, innerFunction forms a closure with outerFunction’s scope. Even after outerFunction has returned, innerFunction still has access to outerVariable because of the creating a closure. This allows data to persist without resorting to global variables, enabling safer, more modular programming. You can also create closures implicitly, for example when using event handlers or callbacks. The key takeaway is that any function that references variables from its outer scope automatically becomes a closure, whether you explicitly return it or not.

      Course Curriculum

      Develop Your Skills with Full Stack Training Course Certification Course

      Weekday / Weekend BatchesSee Batch Details

      Practical Examples of Closures

      Closures are not just a theoretical concept, they have numerous practical applications in everyday JavaScript programming. One common example is creating private variables. JavaScript doesn’t have a built-in mechanism for private properties, but closures can simulate them:

      • function counter() {
      • let count = 0;
      • return {
      • increment: function () {
      • count++;
      • console.log(count);
      • },
      • decrement: function () {
      • count–;
      • console.log(count);
      • }
      • };
      • }
      • const myCounter = counter();
      • myCounter.increment(); // 1
      • myCounter.increment(); // 2
      • myCounter.decrement(); // 1

      In this example, count is not accessible directly from the outside counter, but can still be manipulated through the closure functions increment and decrement. Another example is in asynchronous code, where closures capture the state at the time the function was created:

      • function delayedMessage(message, delay) {
      • setTimeout(function () {
      • console.log(message);
      • }, delay);
      • }
      • delayedMessage(“Hello after 2 seconds”, 2000);

      Here, the callback passed to setTimeout forms a closure with the variable message, ensuring that the correct message is logged after the delay.


      Are You Interested in Learning More About Full Stack Training Course? Sign Up For Our Full Stack Training Course Today!


      JavaScript Closure in Loops

      A classic closure pitfall appears in loops. Consider this example:

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

      You might expect the output to be 1, 2, 3, but instead, you get 4, 4, 4. This happens because var is function-scoped, so all the inner functions share the same i variable, which ends up being 4 after the loop finishes.

      JavaScript Closure in Event Handlers

      Event handling in JavaScript relies heavily on closures. When you attach an event listener to an element, the callback function can access variables from the scope in which it was created, even if the event is triggered much later.

      JavaScript Closure in Event Handlers Article
      • function setupButton(buttonId, message) {
      • const button = document.getElementById(buttonId);
      • button.addEventListener(‘click’, function () {
      • console.log(message);
      • });
      • }
      • setupButton(“myBtn”, “Button clicked!”);

      Here, the event handler function forms a closure with a message. Even though setupButton may have finished executing long before the button is clicked, the event handler still has access to the message. Closures in event handlers make it possible to customize behavior for each element without resorting to global variables or complex object structures. This pattern is extremely common in UI development, especially when building interactive web applications.


      Gain Your Master’s Certification in Full Stack Developer Training by Enrolling in Our Full Stack Developer Master Program Training Course Now!


      Memory Management in Closures

      Closures retain references to variables in their outer scope, which can sometimes lead to memory leaks if not managed properly. Since the closure prevents garbage collection of the referenced variables, those variables remain in memory as long as the closure exists. For example, if you store a closure in a global variable or attach it to a long-lived DOM element, it will keep its captured variables in memory until the closure itself is dereferenced. In large applications, this can become a problem.

      Memory Management in Closures Article

      To avoid memory issues:

      • Remove event listeners when they are no longer needed.
      • Nullify references to closures that are no longer in use.
      • Avoid creating closures in tight loops unless necessary.

      Modern JavaScript engines handle closures efficiently, but being aware of how they work helps you write memory-conscious code.


      Preparing for Full Stack Training Job Interviews? Have a Look at Our Blog on Full Stack Developer Interview Questions and Answers To Ace Your Interview!


      Use Cases of Closures

      Closures have numerous practical uses in JavaScript development:

      • Data Privacy: Encapsulate variables to prevent external modification.
      • Function Factories: Generate customized functions dynamically.
      • Partial Application and Currying: Pre-fill arguments for later execution.
      • Stateful Functions: Maintain state across multiple function calls.
      • Callbacks and Event Handling: Retain access to the environment where the callback was created.
      • Module Pattern: Organize code into self-contained units with private data.

      By mastering closures, you unlock the ability to write more expressive, reusable, and secure code.


      Debugging Closures

      Debugging closures can be tricky because the values of variables might not be what you expect when the closure runs. To tackle this issue, you can use tools like the browser developer console. This tool lets you inspect the function’s scope and see the variables it captures at runtime. Here are some helpful debugging tips: First, use clear names for your functions to improve clarity in stack traces. Next, log the variable values when the closure is created to make sure they are correct. Use `let` or `const` instead of `var` to avoid accidental sharing of variables. Also, stepping through your code with breakpoints can help you observe the behavior of scopes in real-time. By developing a strong understanding of closures, you’ll find it easier to troubleshoot unexpected behaviors, as you’ll know what to monitor.


      Interview Questions on Closures

      Closures are a favorite topic in JavaScript interviews. You might encounter questions like: To prepare for such technical deep-dives, exploring Full Stack Developer Training reveals how mastering JavaScript fundamentals including closures, scopes, and execution contexts equips candidates to tackle interview challenges and build production-ready applications across the stack.

      • Explain what a closure is in JavaScript.
      • Give a practical use case for closures.
      • Demonstrate how to create private variables using closures.
      • Why does the following code print 4, 4, 4 instead of 1, 2, 3?
      • How can closures cause memory leaks, and how can you prevent them?

      Interviewers use closure questions to test your understanding of scope, lexical environments, and function behavior core concepts that define JavaScript proficiency.

    Upcoming Batches

    Name Date Details
    Full Stack Developer Training

    22 - Sep- 2025

    (Weekdays) Weekdays Regular

    View Details
    Full Stack Developer Training

    24 - Sep - 2025

    (Weekdays) Weekdays Regular

    View Details
    Full Stack Developer Training

    27 - Sep - 2025

    (Weekends) Weekend Regular

    View Details
    Full Stack Developer Training

    28 - Sep - 2025

    (Weekends) Weekend Fasttrack

    View Details