Closure

Closure

In this Blog we will try to understand what is closure in JavaScript and what is the benefit of it .

Closure in JavaScript is a powerful concept that allows functions to retain access to variables from their parent scope, even after the parent function has finished executing. In simpler terms, a closure is created when a function is defined inside another function and the inner function can access variables from the outer function.

  1. When a function is defined inside another function, the inner function forms a closure.

  2. The closure includes the inner function itself and all the variables that were in scope when the closure was created.

  3. The inner function has access to its own local variables, the variables of the outer function, and any global variables.

  4. Once the outer function finishes executing, the closure still retains access to the variables it needs.

  5. Closures are commonly used for data privacy, encapsulation, and creating function factories.

Let's illustrate this concept with an example:


function outerFunction() {
  var outerVariable = 'I am from the outer function';

  function innerFunction() {
    console.log(outerVariable); // Accessing the outerVariable from the closure
  }

  return innerFunction; // Returning the inner function
}

var closure = outerFunction(); // The outer function is executed, and innerFunction is assigned to the closure variable.
closure(); // Logs: "I am from the outer function"

In the example above, the innerFunction is defined inside the outerFunction. It forms a closure that includes the innerFunction itself and the outerVariable. Even after the outerFunction finishes executing and returns the innerFunction, the closure still has access to the outerVariable. When closure() is called, it logs the value of outerVariable stored in the closure.

Closures can be a bit tricky to grasp at first, but once you understand them, they provide a powerful mechanism for managing state and controlling access to variables in JavaScript.

Certainly! Here are some easy examples that demonstrate closures in JavaScript

Example 1: Counter Function


function createCounter() {
  var count = 0;

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

var counter = createCounter();
counter(); // Logs: 1
counter(); // Logs: 2

In this example, the createCounter function returns an inner function that increments and logs the count variable. The count variable is stored in the closure of the returned function, allowing it to retain its value between multiple function calls.

Example 2: Private Variable

function createPerson(name) {
  var privateName = name;

  return {
    getName: function() {
      return privateName;
    },
    setName: function(newName) {
      privateName = newName;
    }
  };
}

var person = createPerson('John');
console.log(person.getName()); // Logs: "John"
person.setName('Alice');
console.log(person.getName()); // Logs: "Alice"

In this example, the createPerson function creates an object with two methods: getName and setName. The privateName variable is accessible only within the closure of the returned object. This creates a private variable that can be accessed and modified using the provided methods.

Example 3: Event Handlers

function addClickHandlers() {
  var buttons = document.getElementsByTagName('button');

  for (var i = 0; i < buttons.length; i++) {
    var button = buttons[i];
    button.addEventListener('click', function() {
      console.log('Button ' + i + ' clicked.');
    });
  }
}

addClickHandlers();

In this example, the addClickHandlers function adds click event handlers to a collection of buttons. The event handlers are defined within a loop, but they all share the same closure, which includes the i variable. However, due to closures, when the event handlers are executed, they can access the correct value of i even after the loop has finished.

Closures provide a way to create encapsulated and private data, manage state, and preserve access to variables. They are widely used in JavaScript to implement various patterns and achieve more flexible and powerful code structures.