DEV Community

Jekin Gohel
Jekin Gohel

Posted on

Understanding Closure in JavaScript: A Comprehensive Guide

Description:
Closure is an important idea in JavaScript that can be tricky to grasp but is key for understanding more advanced topics like functional programming and asynchronous programming. In this guide, we'll explain closure in simple terms, covering what it is, why it matters, and showing some real-life examples.

What is Closure?
Closure means that a function can remember and use variables from outside its own scope, even after the outer function has stopped running. This allows inner functions to keep accessing those variables, even if they aren't passed in as arguments.

The Basics of Closure: Lexical Scope
Understanding closure starts with knowing about lexical scope. Lexical scope means that inner functions can see and use variables from the functions they're inside of. But, lexical scope is just part of closure. Closure also includes the idea that these inner functions remember those variables even after the outer function is done.

// Example of Lexical Scope
let x = 1;

const parentFunction = () => {
    let myValue = 2;
    console.log(x); // Accessing global scope variable
    console.log(myValue); // Accessing local scope variable

    const childFunction = () => {
        console.log(x += 5); // Modifying global scope variable
        console.log(myValue += 1); // Modifying local scope variable
    }

    return childFunction;
}

const result = parentFunction();
result(); // Calling the child function
Enter fullscreen mode Exit fullscreen mode

In this example, childFunction can see and change the variables x and myValue from parentFunction even after parentFunction has finished running.

Closure in Action: Private Variables
One common use of closures is to create private variables. This means keeping variables inside a function so they can't be accessed directly from outside the function. This helps keep data safe and organized.

// Example of Private Variables Using Closure
const privateCounter = (() => {
    let count = 0;
    console.log(`Initial value: ${count}`);

    return () => {
        count += 1;
        console.log(count);
    }
})();

privateCounter(); // Output: 1
privateCounter(); // Output: 2
Enter fullscreen mode Exit fullscreen mode

In this example, count is a private variable that can only be changed by the function returned by the outer function. This keeps count safe from outside changes.

Practical Example: Arcade Game Credits
Another way to use closure is to manage things that change over time, like tracking credits in an arcade game. With closure, we can create a function that keeps track of how many credits are left and reduces them each time you play.

// Example of Arcade Game Credits Using Closure
const credits = ((num) => {
    let credits = num;
    console.log(`Initial credit value: ${credits}`);

    return () => {
        credits -= 1;
        if (credits > 0) console.log(`Playing game, ${credits} credit(s) remaining`);
        if (credits <= 0) console.log("Not enough credits");
    }
})(3);

credits(); // Output: Playing game, 2 credit(s) remaining
credits(); // Output: Playing game, 1 credit(s) remaining
credits(); // Output: Not enough credits
Enter fullscreen mode Exit fullscreen mode

In this example, the credits function keeps track of the number of credits and reduces it by 1 each time you call it. When the credits run out, it lets you know.

Conclusion
Closure is a useful feature in JavaScript that lets developers create private variables, manage changing data, and come up with smart solutions to tricky problems. By learning how closure works and how to use it, you can make the most of what JavaScript can do.

Happy coding! 🚀

Top comments (0)