9

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?

TylerH
  • 20,799
  • 66
  • 75
  • 101
dgo
  • 3,877
  • 5
  • 34
  • 47
  • 4
    The `var`s 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 Jan 22 '16 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 Jan 22 '16 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 Jan 22 '16 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 Jan 22 '16 at 17:28
  • Possible duplicate of [JavaScript variables declare outside or inside loop?](http://stackoverflow.com/questions/3684923/javascript-variables-declare-outside-or-inside-loop) – K Scandrett Mar 14 '17 at 01:34

2 Answers2

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

   }
Crashalot
  • 33,605
  • 61
  • 269
  • 439
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • The first part of your answer answered my initial question, I think. You are saying purely cosmetic? (Not that cosmetic is unimportant, but not critical when working in the console). But the second part of your question raised another question for me. Does all the DOM lookup happen when `liTags` grabs all the `LI` elements? If so, the iteration becomes no different than iterating over any other *array-like* object? See also my comment on @bultack answer. – dgo Jan 22 '16 at 17:42
  • 3
    @user1167442 - `getElementsByTagName()` returns a ***live HTMLCollection***. That means that all the elements it finds are there initially, but if the DOM changes while you are using the data structure, the results will be updated live. This can be a blessing and a curse (more often a curse in my opinion) and is something you have to watch out for if you're processing an HTMLCollection while changing the DOM in a way that would affect the HTMLCollection itself. It is sometimes wise to actually copy the HTMLCollection into a static array to prevent it from changing. – jfriend00 Jan 22 '16 at 17:44
  • Thanks. That is super useful for future reference. – dgo Jan 22 '16 at 17:50
3

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;

}
abaracedo
  • 1,404
  • 5
  • 26
  • 45