1

My colleague and I have been discussing good/bad practices of using the var keyword in loops. This is the my way:

for (var i = 0; i < anArray.length; i++) {
    for (var j = 0; j < anotherArray.length; j++) {
        var a1 = someValue1;
        var a2 = someValue2;
        var a3 = someValue3;
        var a4 = someValue4;
        var a5 = someValue5;

        ...... //Some other process that involve a1-5
    }
}

I used var inside nested for loops. Suppose loop i runs for 2000 times and j for 3000 times. My colleague claim that using var in loops like these is the cause of memory leak thus, is a bad practice. Is it true?

He says that "var should be declared outside the loop so that the variables are subject to function scope and get destroyed when the scope end." Is this true?

Apart from the above claiming about memory leak, is this a bad practice, if so why?

I'm skeptical since what I know (or maybe believe) using var in loop, a1-5 still get destroyed when this function ends.

Luke Peterson
  • 8,584
  • 8
  • 45
  • 46
Mysteltainn
  • 421
  • 3
  • 5
  • 13
  • it doesn't matter where you put the `var` keyword. Variables in Javascript always have function scope. – Barmar Jul 09 '14 at 09:48
  • 2
    This has bee answered already http://stackoverflow.com/questions/3684923/javascript-variables-declare-outside-or-inside-loop – Gio Polvara Jul 09 '14 at 09:50
  • 1
    @Gpx thx. That didn't comes up when I searched. Maybe it's because I use 'var keyword' in searching :( – Mysteltainn Jul 09 '14 at 09:56

2 Answers2

2

Variables get hoisted, which means that to the JavaScript interpreter, your code looks like this:

var i, j, a1, a2, a3, a4, a5;
for (i = 0; i < anArray.length; i++) {
    for (j = 0; j < anotherArray.length; j++) {
        a1 = someValue1;
        a2 = someValue2;
        a3 = someValue3;
        a4 = someValue4;
        a5 = someValue5;

        ...... //Some other process that involve a1-5
    }
}

So it makes no difference at all where you declare them - they have function scope anyway.

There is a somewhat valid argument however (though it may be debatable), that you should declare all your variables at the top of your functions, so that the code looks the same to you as it does to the interpreter, and you don't get confused thinking that variables declared inside a block are not valid elsewhere. It's just personal preference I guess.

Gio
  • 841
  • 1
  • 5
  • 11
0

This is purely a style issue, and should have no impact on performance or memory use. Variables in Javascript have function scope no matter where in the function they're declared. When the function is compiled, all the variable declarations are hoisted to the top of the function.

Barmar
  • 741,623
  • 53
  • 500
  • 612