-1

Which usage of var is correct:

$( 'li' ).each( function()
{
    var item = $( this );

    // ...
});

or

var item;

$( 'li').each( function()
{
    item = $( this );

    // ...
});

Both work fine, even having 'use strict'. Is there any fundamental difference between these two?

Thank you.

Osvaldas
  • 160
  • 1
  • 12

4 Answers4

2

It depends on the result you want. In the first case, the variable is declared inside a function, which means it is unique to each iteration/function invocation and not accessible outside the loop/function.

The second case allows you to access the variable outside the function/loop, where it will contain the value of the last iteration.

deceze
  • 510,633
  • 85
  • 743
  • 889
0

Optimizations like this, in the long run, probably do not matter.

Please checkout out the JSPerf below:

http://jsperf.com/declaring-variables-inside-loops/4 http://jsperf.com/declaring-variables-inside-loops/11

Seems there is still a debate going on :P

Kyle
  • 1,058
  • 2
  • 10
  • 22
0

If it were a "normal loop" (ie. for) then your first block of code would be technically incorrect (at least from a human-readability, least-surprise standpoint).

But because you have a jQuery iteration function with a callback, there is actually a difference. That difference being that the last value of item will be accessible outside the loop in the second block of code, but in the first block it will be kept inside the closure.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

There is.

Since in JavaScript variables are function-scoped, in first case variable will exist only inside anonymous function, declared in iterator, and will be allocated on each run, each time it will be a new variable.

In second case function is bounded to some outer scope, and it will be exactly the same variable on each iteration, preserving value, stored on previous execution

Words "allocated on each iteration" can sound frightening, but basically it's not a problem, JS engines like V8 can easily perform optimisation, which will reduce overhead to 0. I'd say it's a recommended way of declaring variables - bound them to the tightest reasonable scope.

Speaking about second case - since no things would be broken, it's generally a bad design practice since some garbage old-stored value can leak to some other context, variable can be caught by some unexpected closure on continuation, etc.. Use local variables as really local.

Meredian
  • 930
  • 8
  • 23