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
}