Declaring a Javascript variable inside a loop

I have a habit that I get caught on the edge, but I think it can be completely unnecessary. With type code:

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 compulsively declare a variable before the loop, and not:

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

Note that in the second code block, I define a variable with vareach time the loop repeats. I guess the first is best practice for readability, etc. But sometimes I just hack something and don’t need best practice.

My question is:

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

+4
2

- Javascript var, for. , , .

, Javascript hoisting , , , , , . var . , - .

, , , . var for, , for, . , . , let var, let , var .

, , , . , var , , .

, , :

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

document.getElementsByTagName() , .


2017 . Javascript ES6, const, let . , , var, , for, , for. , , , , , . const let, , , .

  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 own a and b
          // variables to use here, which would not be the case with var
      });

   }
+10

, , , , a DOM, . , 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;

}
+2

Source: https://habr.com/ru/post/1625548/


All Articles