最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

performance - Javascript variable declaration within loop - Stack Overflow

programmeradmin2浏览0评论

I have a habit that I am borderline compulsive about, but I think may be completely unnecessary. With code like:

function abc(){
  var a,b;
  for(var i=0;i<10;i++){
    a=document.getElementsByTagName('LI').item(i).width;
    b=document.getElementsByTagName('DIV').item(i).width;
    // now do something with a and b
   }
   return;
}

I am compulsive about declaring the variable before the loop as opposed to:

function abc(){
  for(var i=0;i<10;i++){
   var a=document.getElementsByTagName('LI').item(i).width;
   var b=document.getElementsByTagName('DIV').item(i).width;
    // now do something with a and b
   }
   return;
}

Notice that in the second code block, I define the variable with var each time the loop iterates. I imagine the first is best practice for readability, etc. But sometimes I'm just hacking something and don't need to follow best practice.

My question is:

Is there any reason not to define a variable that will be getting redefined using the var keyword inside a loop?

I have a habit that I am borderline compulsive about, but I think may be completely unnecessary. With code like:

function abc(){
  var a,b;
  for(var i=0;i<10;i++){
    a=document.getElementsByTagName('LI').item(i).width;
    b=document.getElementsByTagName('DIV').item(i).width;
    // now do something with a and b
   }
   return;
}

I am compulsive about declaring the variable before the loop as opposed to:

function abc(){
  for(var i=0;i<10;i++){
   var a=document.getElementsByTagName('LI').item(i).width;
   var b=document.getElementsByTagName('DIV').item(i).width;
    // now do something with a and b
   }
   return;
}

Notice that in the second code block, I define the variable with var each time the loop iterates. I imagine the first is best practice for readability, etc. But sometimes I'm just hacking something and don't need to follow best practice.

My question is:

Is there any reason not to define a variable that will be getting redefined using the var keyword inside a loop?

Share Improve this question edited Feb 2, 2016 at 4:09 TylerH 21.1k77 gold badges79 silver badges112 bronze badges asked Jan 22, 2016 at 17:16 dgodgo 3,9376 gold badges36 silver badges50 bronze badges 5
  • 4 The vars will get hoisted anyway, including the one in the for statement. IMO not declaring them at the top of the function (including the one you don't) carries an implication that hoisting doesn't exist, and just makes things harder to think about, especially when a future reader might not fully grok JS. And it's just noise. – Dave Newton Commented Jan 22, 2016 at 17:18
  • The only time you need to use VAR is when the variable will be held outside (global). Doing this inside a function means whether you VAR it or not, it drops when the function is done anyway. It doesn't matter if you do it inside a loop or not. It's because it's inside the function that it's useless. – durbnpoisn Commented Jan 22, 2016 at 17:23
  • @durbnpoisn. Um - maybe I'm misunderstanding you, but that seems like the opposite of my understanding. If I don't use the var keyword to define a variable within a function, it will get pulled into the global scope - and thus create other issues unrelated to this question. – dgo Commented Jan 22, 2016 at 17:27
  • @DaveNewton. So is it purely cosmetic then? Assuming, I'm hacking in the developer console and don't care about readability, is it for all intents and purposes, the same? – dgo Commented Jan 22, 2016 at 17:28
  • Possible duplicate of JavaScript variables declare outside or inside loop? – K Scandrett Commented Mar 14, 2017 at 1:34
Add a comment  | 

2 Answers 2

Reset to default 22

Because of variable hoisting in Javascript, there is no technical difference in execution between the var being at the top of the function or inside the for loop. If that is all you care about, then you can do it either way.

Just to refresh memory, Javascript hoisting means that code like your second code block is parsed and then execute just like your first code block. All var declarations within a function are automatically moved to the top of the function scope before execution. Assignments to those variables are kept where they are located in the code - just the declaration of the variable is moved.

So, the difference is more about how you want to code to look. When you put the var definitions inside the for loop, it makes the code look like the variables are being created anew for each iteration of the for loop, even though that is not the case. They are being assigned a value each iteration of the loop, but a new variable is not created. That would be the case if you used let instead of var since let has a block scope whereas var only has function scope.

In general, it is a good practice to only put code inside a loop that actually needs to be inside the loop. While it doesn't actually change anything in the execution whether the var is inside or outside the loop, it is just part of a good practice whereas other code being inside or outside the loop could make a difference.

In your case, I think this would be a better practice:

function abc(){
  var liTags = document.getElementsByTagName('LI');
  var divTags = document.getElementsByTagName('DIV');
  var len = Math.min(liTags.length, divTags.length);
  var a,b;

  for(var i = 0; i < len; i++){
    a = liTags[i].width;
    b = divTags[i].width;

    // now do something with a and b

   }

   return;
}

Here, you've removed the two calls to document.getElementsByTagName() from the loop which will make a HUGE performance difference.


Update in 2017. Javascript version ES6, now supports both const and let for declaring variables. They are block scoped, not function scoped like var, so if you declare one of them inside a for loop block, then there will be a new and separate variable created for each invocation of the for loop. While that wouldn't make any significant execution difference in the type of code you showed, it can make a difference if you had asynchronous code inside the loop that references the variable you were declaring. In the case of const or let used within the loop body, each asynchronous call would get its own separate copy of the variable which can sometimes be very handy.

  for(var i = 0; i < len; i++){
      let a = liTags[i].width;
      let b = divTags[i].width;
      
      $.get(someUrl).then(function(data) {
          // each call to $.get() here in the loop has it's own a and b
          // variables to use here, which would not be the case with var
      });

   }

I know that this answer is not going to help with your question, it's just an advice, but I think that's a good practice to put in a variable a DOM element when you're going to access it more than one time. Doing this you avoid to iterate each time over all the DOM.

function abc() {

  var a = document.getElementsByTagName('LI'),
      b = document.getElementsByTagName('DIV');

  for ( var i = 0; i < 10; i++ ) {

    a.item(i).width;
    b.item(i).width;
    // now do something with a and b

   }

   return;

}
发布评论

评论列表(0)

  1. 暂无评论