In a loop, is it better to redefine a global variable or to redefine and redefine a local variable several times, or is there no difference?

advertisements

For example:

is

for(var i = 1; i<100; i++){
  var inc = 1/i*PI;
  //and so forth
}

in any way better or worse than

var inc = 1/1*PI;
for(var i = 1; i<100; i++){
  inc = 1/i*PI;
}

Of course the first is easier to type, but maybe it takes away speed/performance (even if a little bit) from the program when constantly re-declaring the same variable versus reassigning values to a global variable. Thank you.


The second approach is correct. You should only declare variables once.

I would code your example like so:

var i,inc = 1/1*PI;
for(i = 1; i<100; i++){
  inc = 1/i*PI;
}

This puts all the variable declarations in one place which makes it easier to read the code.

If you would like to use block level scope, use the let statement, like so:

var i;
for(i = 1; i<100; i++){
  let inc = 1/i*PI;
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let