TobilobaCodes – LeetCode Explorer

2620. Counter

In this page, we will discuss LeetCode Problem 2620: Counter. This problem requires you to implement a function that returns a counter function. This counter function initially returns n and then returns 1 more than the previous value every time it is called.

📄 Problem Statement

Given an integer n, return a counter function. This counter function initially returns n and then returns n + 1, n + 2, and so on each time it is called.

💡 Example

Input:
const counter = createCounter(10);
counter(); // 10
counter(); // 11
counter(); // 12

🧠 Explanation

This problem is testing your understanding of closures in JavaScript. When you call createCounter(n), it returns a function that "remembers" the value of n. Each time you call this returned function, it increases n by 1 and returns the previous value.

You can solve this by using the let keyword to create a persistent counter that updates and returns the correct sequence.

✅ My Solution


var createCounter = function(n) {
    return function() {
        return n++;
    };
};