Closures in JavaScript

Closures in JavaScript
----------------------------------------------

Closures in JavaScript are a powerful concept where a function retains access to its surrounding scope even after the outer function has finished executing. This allows the inner function to access variables and parameters of its outer function, even though the outer function has already completed its execution.

Here's an example to illustrate closures:

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

  function innerFunction() {
    console.log(outerVariable); // Accesses outerVariable from the outer scope
  }

  return innerFunction; // Returning the inner function
}

let closure = outerFunction(); // The outer function executes and returns the inner function

closure(); // Invoking the inner function, which still has access to outerVariable

 

In this example, outerFunction() defines outerVariable and innerFunction inside it. When outerFunction() is called, it creates a closure by returning innerFunction. Even after outerFunction() finishes executing, the closure variable still holds a reference to innerFunction, along with its surrounding scope. Thus, when closure() is called later, it can access outerVariable because of the closure, even though outerFunction() has already completed execution.

Closures are often used to create private variables and encapsulation in JavaScript. They allow you to maintain state and create functions that "remember" their lexical environments.

function createCounter() {
  let count = 0;

  return {
    increment: function() {
      count++;
      console.log('Count:', count);
    },
    decrement: function() {
      count--;
      console.log('Count:', count);
    },
    getCount: function() {
      return count;
    }
  };
}

let counter = createCounter();
counter.increment(); // Output: Count: 1
counter.increment(); // Output: Count: 2
counter.decrement(); // Output: Count: 1
console.log(counter.getCount()); // Output: 1

 

Here, createCounter() creates a closure that contains count and returns an object with methods to manipulate count. The count variable is accessible only through the returned object's methods, providing a way to maintain private state. Each time increment() or decrement() is called, it modifies the count variable, and getCount() returns its current value.

 

Categories: Java Script Tags: #ES6, #JavaScript,

Newsletter Subcribe

Receive updates and latest news direct from our team. Simply enter your email.