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?
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
ivariable will be scoped to the enclosing variable environment, whether the enclosing environment is a function, or the global environment.