DEV Community

Midhul P
Midhul P

Posted on

2

A Beginner's Guide to JavaScript Closures

In JavaScript, a closure is a function that retains access to variables from its parent scope, even after the parent function has completed. This unique behaviour allows functions to "remember" their context, making closures invaluable for managing private data and structuring complex code.

Why Use Closures?

Closures are essential for creating private variables and encapsulated logic. By wrapping functionality in a closure, you can protect variables from external interference, keeping code organised and secure.

Example of a Closure: Simple Counter

Here's a common use of closures, where we build a counter function that retains a private count variable:

function makeCounter() {
    let count = 0;

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

let counter = makeCounter();
counter(); // Logs: 1
counter(); // Logs: 2
counter(); // Logs: 3
Enter fullscreen mode Exit fullscreen mode

Each time counter() is called, it accesses and increments the private count variable, which is only accessible inside makeCounter.

Real-World Example: Login Manager

Closures are also useful for more complex scenarios, like managing user login states. Here’s a login manager with private state control:

function createLoginManager() {
    let isLoggedIn = false;

    return {
        login: function() { isLoggedIn = true; },
        logout: function() { isLoggedIn = false; },
        isLoggedIn: function() { return isLoggedIn; }
    };
}

let loginManager = createLoginManager();
console.log(loginManager.isLoggedIn()); // false
loginManager.login();
console.log(loginManager.isLoggedIn()); // true
Enter fullscreen mode Exit fullscreen mode

The isLoggedIn variable is encapsulated within createLoginManager, accessible only through the returned methods. This approach keeps login information secure and well-organized.

Conclusion

Closures might seem tricky at first, but they’re a powerful tool for organizing JavaScript code, making it both secure and maintainable.

To explore more about JavaScript closures with additional examples and insights, check out my full article on Medium: What is JavaScript Closures? A Practical Guide.

Happy coding!

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more