JS function that returns consecutive number (in asceding order) every time it's called

Hi.
I’m trying to write a function that returns consecutive numbers every time it’s called.
f.e
1st call: 0
2nd call: 1
3rd call: 2

and 3, 4 and so on.
The catch is i cannot use any variables outside the function or any input arguments. Any tips how to do this?

What you’re looking for is a type of higher-order function called a closure, and a counter is one of the simplest examples. It does actually use a variable “outside” the function, but it’s not a global variable, or even one that anything else can access.

function makeCounter() {
    let count = 0;
    return function() {
        return count++
    }
}

You’d use it like so:

let counter = makeCounter()
counter()   // 0
counter()   // 1
counter()   // 2
... and so on

The way this works is because the function returned has access to the count variable, even after makeCounter returns. It’s said to have “captured” the count variable, which is what makes it a closure. The really neat thing is, every counter is independent, because it gets its own copy of count

let counter1 = makeCounter()
let counter2 = makeCounter()
counter1() // 0
counter1() // 1
counter2() // 0
counter2() // 1
2 Likes