start learning
Image 1

Javascript closure

In JavaScript, a CLOSURE is a combination of a function and the lexical environment within which that function was declared. It refers to the ability of a function to access variables from its outer (enclosing) scope even after the outer function has finished executing.

When a function is defined inside another function, the innerFunction has access to its own local variables, as well as the variables and parameters of the outerFunction. This is because the innerFunction has access to the scope chain, which consists of its own scope and the scopes of all the outerFunctions.
Here's an example to illustrate the concept of closure :


// Define an outer function
function outerFunction() {
  var outerVariable = 'I am from the outer function!';

  // Define an inner function
  function innerFunction() {
    // Log the value of outerVariable from the outer scope
    console.log(outerVariable); 
  }

  // Return the inner function
  return innerFunction; 
}

// Call outerFunction and assign the returned inner function to 'closure'
var closure = outerFunction(); 

// Invoke the inner function stored in 'closure'
closure(); 

In this example, the innerFunction is defined inside the outerFunction and it has access to the outerVariable even after the outerFunction has finished executing. The outerFunction returns the innerFunction, which is then assigned to the variable closure. When closure is invoked, it still has access to the outerVariable and logs its value.
example that showcases closures in JavaScript :


Closure Example 1

In this example, we have an HTML page with a button. When the button is clicked, the invokeClosure function is triggered. This function, in turn, invokes the closure function, which is the inner function returned by outerFunction.


<!DOCTYPE html>
<html>
<head>
  <title>Closure Example</title>
  <script>
    function outerFunction() {
      var outerVariable = 'I am from the outer function!';

      function innerFunction() {
        alert(outerVariable); // Accessing outerVariable from the outer scope
      }

      return innerFunction; // Returning the inner function
    }

    var closure = outerFunction(); // Assigning the returned inner function to a variable

    function invokeClosure() {
      closure(); // Invoking the inner function
    }
  </script>
</head>
<body>
  <button onclick="invokeClosure()">Click me</button>
</body>
</html>

When the closure function is invoked, it accesses the outerVariable from its enclosing scope (i.e., the outerFunction). The value of outerVariable is then displayed in an alert box.

The closure is created when the outerFunction is called and assigns the inner function to the variable closure. Even after the outerFunction has finished executing, the closure still has access to the outerVariable due to closure's property of maintaining the lexical scope.

So, when you click the button, it triggers the invokeClosure function, which in turn invokes the closure function, displaying the message "I am from the outer function!" in an alert box.


Closure Example 2

In this example, we have an HTML page with two buttons labeled "Increment" and "Decrement". The goal is to create a counter that increases or decreases its value when these buttons are clicked.


<!DOCTYPE html>
<html>
<head>
  <title>Closure Example</title>
  <script>
    // Define a function to create a counter object
    function createCounter() {
      // Initialize a count variable
      var count = 0;

      // Define a function to increment the count
      function increment() {
        count++;
        console.log(count);
      }

      // Define a function to decrement the count
      function decrement() {
        count--;
        console.log(count);
      }

      // Return an object with increment and decrement methods
      return {
        increment: increment,
        decrement: decrement
      };
    }

    // Create a counter object by calling createCounter function
    var counter = createCounter();

    // Define a function to increment the counter
    function incrementCounter() {
      counter.increment();
    }

    // Define a function to decrement the counter
    function decrementCounter() {
      counter.decrement();
    }
  </script>
</head>
<body>
 // Display a header for the counter
 <p>Counter</p>

 // Display the count with an initial value of 0
 <p>Count: <span id="count">0</span></p>

 // Create buttons for incrementing and decrementing the counter
 <button onclick="incrementCounter()">Increment</button>
 <button onclick="decrementCounter()">Decrement</button>
 </body>
</html>

The createCounter function is defined, which internally declares a count variable and two inner functions: increment and decrement. These inner functions have access to the count variable due to the closure formed by the createCounter function.

The createCounter function returns an object with the increment and decrement functions as properties. These functions allow us to interact with the counter by incrementing or decrementing its value.

In the HTML section, we have event handlers (onclick) attached to the buttons. When the "Increment" button is clicked, the incrementCounter function is called, which in turn calls the increment function of the counter object. The same applies to the "Decrement" button and the decrementCounter function.

The current count is logged to the console (console.log) for demonstration purposes, but you can modify the code to update the count display on the HTML page if desired.

you can use the code bellow that include the necessary update the count display on the HTML page :


// Define an HTML document
<!DOCTYPE html>
<html>
<head>
  // Set the document title
  <title>Closure Example</title>
   <script>
    // Define a function to create a counter object
    function createCounter() {
      var count = 0;

      // Define a function to increment the count
      function increment() {
        count++;
        updateCount();
      }

      // Define a function to decrement the count
      function decrement() {
        count--;
        updateCount();
      }

      // Define a function to update the count displayed in the HTML
      function updateCount() {
        var countElement = document.getElementById("count");
        countElement.textContent = count;
      }

      // Return an object with increment and decrement methods
      return {
        increment: increment,
        decrement: decrement
      };
    }

    // Create a counter object by calling createCounter function
    var counter = createCounter();

    // Define a function to increment the counter
    function incrementCounter() {
      counter.increment();
    }

    // Define a function to decrement the counter
    function decrementCounter() {
      counter.decrement();
    }
  </script>
</head>
<body>
 // Display a header for the counter
 <p>Counter</p>

 // Display the count with an initial value of 0
 <p>Count: <span id="count">0</span></p>

 // Create buttons for incrementing and decrementing the counter
 <button onclick="incrementCounter()">Increment</button>
 <button onclick="decrementCounter()">Decrement</button>
 </body>
</html>

Resources for Further Learning

Explore the possibilities and create unique effects on your web pages by using the interactive code editor

HTML

Write and customize HTML code

CSS

Add style and design to your web pages with CSS

JavaScript

Enhance interactivity with JavaScript code

Go to Code Editor