Closure Example

Closure Example

Closures are an important concept in JavaScript that are used to implement data privacy and other advanced programming patterns. In essence, a closure is a function that has access to variables in its outer (enclosing) scope, even after the outer function has returned. This can be useful for creating functions with private state or for implementing higher-order functions that generate other functions.

To demonstrate an example of a closure, let's consider a simple function that returns another function:


function createCounter() {
  let count = 0;
  return function() {
    count++;
    console.log(count);
  };
}

In this code, the createCounter function defines a variable count and then returns an anonymous function that increments the count and logs it to the console. Now, let's call this function twice:


const counter1 = createCounter();
const counter2 = createCounter();

counter1(); // logs 1
counter1(); // logs 2
counter2(); // logs 1

What's happening here is that each time we call createCounter, a new closure is created with its own copy of the count variable. This means that each time we call the returned function, it's operating on a different value of count.

This is just one example of how closures can be used in JavaScript. There are many other patterns and use cases, such as creating private methods or implementing the module pattern. The key takeaway is that closures allow us to create functions with persistent state and behavior, which can be an extremely powerful tool in our programming toolbox.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe