JavaScript variables declare outside or inside loop?

Viewed 102526

In AS3 I believe you should initialise all variables outside loops for increased performance. Is this the case with JavaScript as well? Which is better / faster / best-practice?

var value = 0;

for (var i = 0; i < 100; i++)
{
    value = somearray[i];
}

or

for (var i = 0 ; i < 100; i++)
{
    var value = somearray[i];
}
12 Answers

I prefer combining both readability and performance. So my favourite is to declare variable inside loop, that mean I would have block scope encapsulation.

for (let i = 0, sum = 0; i < count; i++) { // count also be declared here like count = array.length;
  sum = sum + 1;
}

Based on previous provided fiddle performance tests the winner is number 4

Related