0

Is there a way in JavaScript to retain the value of a variable in a function? In the function below, it now returns 1 every time it gets called. I'd like it to return 1, 2, 3, 4 etc on successive calls.

I know I can achieve that by declaring the i variable outside the function, but I don't want to pollute the global variable space with a variable that only get's used inside one function.

    function counter() {
        let i;
        if (!i) i = 0;
        i++;
        return i
    }
technetium
  • 110
  • 2
  • 9
  • `const counter = (() => { let i; return () => { if (!i) ... }})()` — To adapt the duplicate above to your situation. – deceze Feb 21 '23 at 08:18
  • You may also find a [generator function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*) useful for this particular example. – Nick Parsons Feb 21 '23 at 08:18

0 Answers0