Computer >> Computer tutorials >  >> Programming >> Javascript

JavaScript variables declare outside or inside loop?


The ECMA-/Javascript language hoists any variable which is declared with var anywhere to the top of a function. That is because this language does have function scope and does not have block scope like many other C-like languages.

function() {
   for(var a = 0; a < 7; a ++) {
      var b = 100;
   }
}

is the same as

function() {
   var b;
   for(var a = 0; a < 7; a ++) {
      b = 100;
   }
}

But with let, this is not the case. let has lexical scoping. So unless you will need the same variable outside the loop (or if each iteration depends on an operation done to that variable in the previous iteration), it's preferable to declare the scope within which it is used.