On Apr 29, 9:51 pm, SM <servandomont...@gmail.comwrote:
Quote:
I've always wonder if there is diference when declaring and
initializing a varible inside/outside a loop.
Performance-wise, no difference. All vars are processed before the
code executes.
Quote:
What's a better practice?
It depends purely on how you want to organize your code.
It's potentially dangerous to not use 'var' in a loop variable because
you could reference a global variable. So, putting 'var' tightly
coupled to the loop is a good idea. It makes sure you aren't using a
global var, and if you copy and paste the code to another function
your var will go with it.
For variables with semantic meaning that hold values you want to do
something real with, it's not a bad idea to declare them at the top so
you know what you're going to work within inside the function. Also,
declaring them at the top with
var name,age,size;
rather than a 'var' before each use saves a few bytes of space ;)
Quote:
As a programmer, i always try to practice good programming. I always
thought that by declaring and initializing the variable inside the
loop, i was creating a new memory space every time instead of just 1
time...
One of the disadvantages of using 'var' inside loops is that it gives
some people the impression that there is block scope in js. There is
not.
Matt Kruse