Sitemap

JavaScript problem solving: Counter

3 min readOct 10, 2023

--

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: 7

Explanation:

  1. The createCounter function takes an initial value n as an argument and returns an inner function.
  2. The inner function, which is returned by createCounter, is a closure that has access to the n variable even after createCounter has finished executing.
  3. Inside the inner function, we use the post-increment operator n++ to increment the value of n by 1 and return the incremented value.
  4. The initial value of n is preserved due to closure, so each time the inner function is called, it returns the next incremented value.
  5. In the usage example, we create a counter with an initial value of 5 by calling createCounter(5), and store the returned function in the counter variable.
  6. When we call counter(), it returns the current value of n (5) and increments it to 6. Subsequent calls to counter() will increment n by 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.

--

--

Pavel Salauyou
Pavel Salauyou

Written by Pavel Salauyou

I build open source software & share knowledge through writing (articles, tutorials). My goal is to make complex topics accessible & help other developers grow.