Search code examples
javascriptloopsglobal-variables

Javascript: Avoid global variable in code involving lots of loops


I'm having a very confusing problem. I think it is best explained with code:

var length = 0; // I want to avoid this variable being global

function loop(array, func) {
	for (var i = 0; i < array.length; i++) {
		array[i].func(length);
		length += array[i].number;
		if (func) {
			func();
		}
	}
}

function bar(number) {
	this.func = function(len) {
		console.log(len);
	};
	this.number = number;
}

function main() {
	var array = [];
	for (var j = 1; j < 3; j++) {
		var foo = new bar(j);
		array.push(foo);
	}
	loop(array, function() {
		loop(array);
	});
}

main();

I have a loop similar to this in some other code. I simply cannot figure out how to make the length variable local in this code. I cannot pass it to the function because it calls itself. I cannot really move it anywhere because the loops keep messing things up.

Thank you for any help!


Solution

  • Not sure exactly what you're trying to accomplish with all this, but it looks like main is the caller of loop, so you can have length be an argument to loop and have main call loop with an initial length of 0 and have loop and the callback return the altered lengths:

    function loop(array, length, func) {
      for (var i = 0; i < array.length; i++) {
        array[i].func(length);
        length += array[i].number;
        if (func) {
          length = func(length);
        }
      }
      return length;
    }
    
    function bar(number) {
      this.func = function(len) {
        console.log(len);
      };
      this.number = number;
    }
    
    function main() {
      var array = [];
      for (var j = 1; j < 3; j++) {
        var foo = new bar(j);
        array.push(foo);
      }
      loop(array, 0, function(newLen) {
        return loop(array, newLen);
      });
    }
    
    main();