DEV Community

Midhul P
Midhul P

Posted on

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!

Top comments (0)