JavaScript problem solving: Counter
In this article we will analyze a simple problem that sometimes occurs in job interviews. I took an example of the problem from https://leetcode.com. And so this is the problem description:
Given an integer n, return a counter function. This counter function initially returns n and then returns 1 more than the previous value every subsequent time it is called (n, n + 1, n + 2, etc).
To solve this problem, we can create a closure in JavaScript. A closure allows a function to retain access to variables from its parent scope even after the parent function has finished executing. In this case, we want the counter function to remember the initial value of n and keep incrementing it.
Here’s the JavaScript code that implements the counter function using closures:
function createCounter(n) {
return function() {
return n++;
};
}
// Usage example:
const counter = createCounter(5);
console.log(counter()); // Output: 5
console.log(counter()); // Output: 6
console.log(counter()); // Output: 7Explanation:
- The
createCounterfunction takes an initial valuenas an argument and returns an inner function. - The inner function, which is returned by
createCounter, is a closure that has access to thenvariable even aftercreateCounterhas finished executing. - Inside the inner function, we use the post-increment operator
n++to increment the value ofnby 1 and return the incremented value. - The initial value of
nis preserved due to closure, so each time the inner function is called, it returns the next incremented value. - In the usage example, we create a counter with an initial value of 5 by calling
createCounter(5), and store the returned function in thecountervariable. - When we call
counter(), it returns the current value ofn(5) and increments it to 6. Subsequent calls tocounter()will incrementnby 1 each time.
That’s it! The counter function created using closures will return the initial value of n and then increment by 1 each time it is called.
Explain closures in JavaScript
In JavaScript, a closure is a special mechanism that allows a function to remember and access variables from its parent scope even after the parent function has finished executing. It’s like a “snapshot” of the variables at the time the function was created.
Get Pavel Salauyou’s stories in your inbox
Join Medium for free to get updates from this writer.
Imagine you have a function, and inside that function, you define another function. The inner function forms a closure because it has access to the variables and parameters of its outer function, even after the outer function has completed its execution.
This means that even if the outer function’s variables would typically go out of scope and be destroyed, the inner function, thanks to the closure, can still “see” and use those variables.
Closures are powerful because they provide a way to create private variables in JavaScript. You can have variables that are accessible only within a specific function, and their values are retained between function calls. This allows you to encapsulate data and behaviour, making it more secure and modular.
Here’s a simple example to illustrate closures:
function outerFunction() {
const privateVariable = 'I am from the outer function';
function innerFunction() {
console.log(privateVariable);
}
return innerFunction;
}
var closureExample = outerFunction();
closureExample(); // Output: 'I am from the outer function'In this example, outerFunction defines an innerFunction and returns it. When we call outerFunction(), it assigns the returned inner function to the variable closureExample. Now, closureExample is a closure that retains access to the privateVariable of its parent function.
When we invoke closureExample(), it still has access to privateVariable and can log its value to the console, even though outerFunction has already finished executing.
Conclusion
Closures are commonly used in JavaScript for various purposes, such as creating private variables, implementing data encapsulation. They provide an elegant way to handle state and preserve data integrity within functions.





