Javascript: Avoid global variable in code involving lots of loops

javascript global variable
change global variable in function javascript
node js access variable outside function
javascript global variable undefined
javascript global variable across files
javascript best practices 2019
node js variable scope
how to make a local variable global in javascript

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();

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();

JavaScript best practices, Don't write code like that — it might make it more art than product, but this is rarely a good thing. Avoid globals. Global variables and function names are an  Avoid Declaring Global Variables We should avoid the use of global variables as much as possible for various reasons. One is that they’re easy to overwrite in different places since they’re

I'm assuming that you want to maintain the value of length between successive function calls of loop. You can do this by returning a closure that uses the length. So, instead of defining loop as you currently do, you could do something like this:

const loop = (function() {
    var length = 0;
    return function (array, func) {
        // Your current code for loop here
    }
}) ();

Basically, what this does is it assigns loop to be a function that is returned from another anonymous function call. This ensures that the value of length persists because it is defined outside of the scope of the function that is eventually assigned to loop, but is entirely inaccessible anywhere else in the code.

JavaScript Best Practices, Well organized and easy to understand Web building tutorials with lots of Avoid global variables, avoid new , avoid == , avoid eval() Local variables must be declared with the var keyword or the let keyword, This also goes for loop variables: It is a good coding practice to initialize variables when you declare them. How and why to avoid global variables in JavaScript - global-variables-are-bad.js When you build SPA/PWA you will not be able to avoid global variables because

Keveloper's answer is a good idea for you. And I would suggest you try that way first.

Here is another way to avoid global variable which may also work.

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

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 (data) {
		loop(array, null, data);
	}, { length: 0 });
}

main();

Variable Scope in Modern JavaScript with var, let and const, It often surprises me when speaking to other JavaScript developers how many are Global variables are declared in the code outside of any function definitions, Thankfully we now have let and const that will help avoid these issues going forward. We can also scope to conditional blocks and loops. Avoid Global Variables We should avoid the use of global variables as much as possible for various reasons. One is that they’re easy to overwrite in different places since they’re available

Demystifying JavaScript Variable Scope and Hoisting, To work with JavaScript efficiently, one of the first things you need to understand is the Any variable declared outside of a function belongs to the global scope, and is therefore accessible from anywhere in your code. inside of a block structure like a for loop, does not restrict that variable to the loop. One trap to avoid is marrying values and functionality in names. A function called isLegalDrinkingAge () makes more sense than isOverEighteen () as the legal drinking age varies from country to country, and there are other things than drinking to consider that are limited by age.

JS loop variable scope, To limit the scope of i to the for-loop's block? However, you hardly will need to do that, since nothing will interfere with it - var i is still scoped local to your function. Sometimes, you even might want to use i after the loop as an ongoing But if you write code in the global scope, "var" has no real sense. Loops can execute a block of code a number of times. Loops are handy, if you want to run the same code over and over again, each time with a different value. The for loop has the following syntax: Statement 1 is executed (one time) before the execution of the code block. Statement 2 defines the condition for executing the code block.

JavaScript closure inside loops – simple practical example, For example, in a loop with a let -based index, each iteration through the loop will have a new variable i with loop scope, so your code would work as you expect. When you declare variable using 'let' even outside the function but inside the loop , this variable will not be a Global variable , it will become a Block level variable which is only available for the same function only.That is the reason , we are getting value of i different for each function when we invoke the functions.

Comments
  • when you declare i and j in for loop, declare using let instead of var
  • @Isaac this isn't using ES6, it's just for a website that I want to be backwards compatible
  • @Isaac While good advice in general, that won't solve anything here
  • What about as a class member?
  • Can you explain more what you want to achieve or what the input and output are? People can help you with those details. Maybe you're solving your problem in a more complicated way than it needs to be.
  • Thanks a lot for this! The code in my original post is just a generalised version of my actual code so the problem is made slightly more obvious. I think I will use your version since it makes a bit more sense to me.