Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript "for (var i = 0; ...) { ... }" browser incompatibilities?

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?

like image 729
thebossman Avatar asked Feb 13 '12 19:02

thebossman


People also ask

Is VAR in JavaScript outdated?

You're right that there is no real reason to write new code using var (except maybe this, if relevant). There are pages on the internet that are decades old though, and no one is going to rewrite them. There is nothing really to gain by removing var from the language.

Which you Cannot use at the time of declaring a variable in JavaScript?

Variable naming There are two limitations on variable names in JavaScript: The name must contain only letters, digits, or the symbols $ and _ . The first character must not be a digit.

How for in loop works in JavaScript?

for/in - loops through the properties of an object. for/of - loops through the values of an iterable object. while - loops through a block of code while a specified condition is true. do/while - also loops through a block of code while a specified condition is true.

What are the 3 parts of a for loop in JavaScript?

JavaScript for loop is used to execute code repeatedly. for loop includes three parts: initialization, condition and iteration.


1 Answers

"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.

like image 199
2 revs, 2 users 94%user1106925 Avatar answered Sep 28 '22 18:09

2 revs, 2 users 94%user1106925