简体   繁体   中英

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

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.

Because of var hoisting , there is absolutely no difference between the two. And since it makes no difference, according to the docs:

For that reason, it is recommended to always declare variables at the top of their scope (the top of global code and the top of function code) so it's clear which variables are function scoped (local) and which are resolved on the scope chain.

Now if you were using let instead of var , the story would be different. I don't think there would be any performance difference at all, but there would certainly then be a semantic difference. The documentation for let goes into detail about those differences.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM