Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript variable declaration within 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?

like image 361
dgo Avatar asked Jan 22 '16 17:01

dgo


People also ask

Can you declare variables in a loop JavaScript?

If a variable is declared inside a loop, JavaScript will allocate fresh memory for it in each iteration, even if older allocations will still consume memory.

Can we use variable in for loop?

Often the variable that controls a for loop is needed only for the purposes of the loop and is not used elsewhere. When this is the case, it is possible to declare the variable inside the initialization portion of the for.

How do you access variables outside a loop?

If you want to access every element of randAd outside the for loop try like this var randAd = []; to initialize it as an array. You can easily access it after your for loop but If you use it as a simple variable var randAd; then you'll get the last variable always (it overwrites).


2 Answers

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

   }
like image 132
jfriend00 Avatar answered Oct 27 '22 20:10

jfriend00


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;

}
like image 37
abaracedo Avatar answered Oct 27 '22 21:10

abaracedo