Tuesday, May 21, 2024
 Popular · Latest · Hot · Upcoming
35
rated 0 times [  36] [ 1]  / answers: 1 / hits: 37306  / 13 Years ago, mon, february 13, 2012, 12:00:00

I haven't done serious JavaScript programming in a while, and I am writing an intro guide to the language for some of my colleagues. I'd like to discuss loop best practices, but there is one small detail I've kept in the back of my head:



When looping over arrays, I remember the following pattern not being safe to use because there are major browsers that don't support it:



for (var i = 0; i < ls.length; i++) { ... }


Instead, the var keyword must be moved out of the array, as such:



var i;
for (i = 0; i < ls.length; i++) { ... }


Is this correct? I've scoured the net and cannot confirm this. Do some old browsers not support the first method? If not, which ones do not?


More From » for-loop

 Answers
12

Is this correct?




Unless we're talking about some really, really old browser, I'm not aware of any such issue with browsers in use today.






The only issue people likely have with the first example is that it may confuse someone into thinking that JavaScript has block scope, which it doesn't This changed since ES6, which does have block scope.



In either example, the i variable will be scoped to the enclosing variable environment, whether the enclosing environment is a function, or the global environment.


[#87496] Sunday, February 12, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
devonw

Total Points: 311
Total Questions: 116
Total Answers: 111

Location: Senegal
Member since Fri, Aug 21, 2020
4 Years ago
;