You can use a closure (here created using an IIFE):
var run = (function() {
var index = 0;
return function run() {
console.log(arr[index]);
if(++index == arr.length) index = 0;
};
}());
But since arr
is global as well, it's not a huge improvement IMO. It would be better (from a code organizational point of view) to pass the array as argument to the function, or also define it inside the IIFE, if it is supposed to be static data.
Alternatively, you could make the index
a property of the function, since functions are just objects. This has the disadvantage(?) that the index would be mutable from the outside (and you make the implementation of the function dependent on the function's name, which is also mutable (which could be solved by using a named function expression instead)):
function run() {
console.log(arr[run.index]);
if(++run.index == arr.length) run.index = 0;
}
run.index = 0;