javascript - Using var when declaring i in a for loop -


this question has answer here:

i've seen javascript code has used 2 different ways of defining loop.

for (var i=0;i < x.length; i++) 

but it's been

for (i=0; < x.length; i++) 

the same thing has happened for-in loops

for (var in x) 

and

for (i in x) 

is there difference between declaring i var , saying i? there advantages of doing 1 on other? 1 these right way this? can tell, both act same, there has difference.

note: i'm not asking difference between for-in , for (i=0)

without var declaration somewhere in function, references i i property of global object. risks sorts of unpredictable behavior if code in body of for loop invokes code (say, inside called method) modifies global i.

note declaring var i in for loop initialization

for (var = ...) 

is equivalent declaring var i; before for loop:

var i; (i = ...) 

in particular, declaration of i hoisted top of enclosing scope.

edit: if enable strict mode, must declare loop variables (all variables, actually). referencing variable has not been declared var statement result in referenceerror being thrown (rather resulting in global variable coming existence).


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -