What is JavaScript Closures – A Practical Guide

javascript Closure Image

Have you ever had a conversation with someone and found yourself struggling to explain a complex topic in a simple and understandable way? Well, that’s how I feel about closures in JavaScript!

What is JavaScript Closure ?

A closure is a function that has access to variables from another function that has already returned. This can be useful for creating private variables and functions, among other things.

When you create a closure, you’re essentially creating a new function that “remembers” the environment in which it was created. This means that the new function has access to variables and parameters from the original function, even after that function has returned.

Where are JavaScript Closure used ?

Closures are commonly used in JavaScript to create private variables and functions. By wrapping a function in another function that returns it, you can create a “private” scope for the inner function that can’t be accessed from outside the closure.

Overall, closures can be a bit tricky to wrap your head around at first. But once you understand how they work, they can be a powerful tool for writing clean, efficient code.

So, let’s dive in and explore the world of JavaScript closures together!

Imagine you have a function that creates another function. The new function has access to the variables and parameters of the function that created it. This is called a closure.

Here’s an example:

// Define the outer function
function outerFunction() {
    // Define a variable within the scope of outerFunction
    var outerVariable = "I'm outside!";
    
    // Define the inner function
    function innerFunction() {
        // innerFunction has access to outerVariable
        console.log(outerVariable);
    }
    
    // Return the inner function from outerFunction
    return innerFunction;
}

// Assign the result of calling outerFunction to closureFunction
var closureFunction = outerFunction();

// Call closureFunction, which is now a closure
closureFunction(); // Outputs: "I'm outside!"

In this example, outerFunction() creates innerFunction(). innerFunction() has access to the outerVariable variable, which is defined in outerFunction().

We then assign closureFunction to the result of calling outerFunction(). closureFunction is now a closure, because it has access to outerVariable.

When we call closureFunction(), it logs the value of outerVariable, which is “I’m outside!”.

Another example:

function makeCounter() {
  let count = 0;

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

let counter = makeCounter();

counter(); // logs 1
counter(); // logs 2
counter(); // logs 3

In this example, makeCounter() creates a function that logs and increments a count variable. We then assign counter to the result of calling makeCounter().

counter is now a closure, because it has access to the count variable. When we call counter() multiple times, it logs the incremented value of count each time.

A closure is a function that has access to variables from another function that has already returned. This can be useful for creating private variables and functions, among other things.

Application in Real World

Let’s say you’re building a web application that needs to keep track of a user’s login status. You want to make sure that the user’s login information is secure and can’t be accessed or manipulated by other parts of the application.

To accomplish this, you could create a function that returns an object with methods to log in, log out, and check the user’s login status. The login information itself would be stored in a private variable that’s inaccessible from outside the closure.

Here’s an example:

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

In this example, createLoginManager() creates a closure that contains the isLoggedIn variable and three methods: login(), logout(), and isLoggedIn().

When we call createLoginManager(), it returns an object with the three methods. We assign this object to the loginManager variable.

We can then call loginManager.login() to log the user in, loginManager.logout() to log them out, and loginManager.isLoggedIn() to check if they’re currently logged in.

The isLoggedIn variable is private and inaccessible from outside the closure, which means that the user’s login information is secure.

The advantages of using a closure for this are twofold:

Security: By keeping the user’s login information in a private variable, we ensure that it can’t be accessed or manipulated by other parts of the application. This makes the login process more secure.

Encapsulation: By wrapping the login logic in a closure, we encapsulate it in a separate scope that’s not accessible from outside the closure. This makes the code cleaner and easier to understand, and helps prevent naming conflicts and other issues.

Closures are commonly used to create private variables and functions, which can help improve code security and encapsulation. They can also be used to create more readable and maintainable code by encapsulating complex logic in a separate scope.

While closures can be a bit tricky to understand at first, they’re a fundamental concept in JavaScript programming that’s worth taking the time to master. With the ability to create secure, efficient, and encapsulated code, closures can help you become a more effective and proficient JavaScript developer.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top