JavaScript’s Closures: An Overview

Posted by

Closures in JavaScript

Closures in JavaScript

One of the most powerful and fundamental concepts in JavaScript is the use of closures. Closures allow you to create private and privileged variables and functions, and they are a crucial part of understanding the inner workings of JavaScript.

A closure is created when a function is defined within another function, and the inner function has access to the outer function’s variables and parameters. This allows the inner function to “close over” the outer function’s scope, capturing its state at the time of creation.

Here’s an example of a closure in JavaScript:


function outerFunction() {
  var outerVariable = 'I am the outer variable';
  
  function innerFunction() {
    console.log(outerVariable);
  }
  
  return innerFunction;
}

var closure = outerFunction();
closure(); // Output: "I am the outer variable"

In this example, innerFunction has access to outerVariable even after outerFunction has finished executing. This is because a closure has been formed, and innerFunction has captured the state of outerVariable at the time of its creation.

Closures are particularly useful for creating private variables and functions. By using closures, you can create encapsulated modules that expose only the necessary functionality, keeping the rest of the variables and functions private.

Here’s an example of using closures to create a private counter:


function createCounter() {
  var count = 0;
  
  return {
    increment: function() {
      count++;
    },
    decrement: function() {
      count--;
    },
    getCount: function() {
      return count;
    }
  };
}

var counter = createCounter();
counter.increment();
counter.increment();
console.log(counter.getCount()); // Output: 2

In this example, count is a private variable that is only accessible through the methods returned by createCounter. This allows us to maintain the integrity of the count variable and only expose the necessary functionality through the returned object.

Understanding closures is crucial for writing clear and maintainable JavaScript code. They allow you to create encapsulated and private modules, leading to more modular and readable code.

0 0 votes
Article Rating
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@gurvirbaraich2028
6 months ago

You could name the add function increment. BYTW nice content