This forum is now read-only. Please use our new forums! Go to forums

0 points
Submitted by fmenot
about 11 years

"var" keyword in for ... in loops

The editor gives me a fatal error every time I attempt to write a for … in loop, stating that I am missing a semicolon. I then come to the forum and find an identical copy, paste it, and voila!

I suspect there may be two issues here, but I toodled on over to W3schools.com and note that they give this syntax for the loop:

for (variable in object)  
  {
  code to be executed
  }

No “var” keyword.

What gives? Are we talking different implementations of Javascript? Is “var” optional? Are there certain objects that require it and others that don’t?

Just asking.

Edit by @joahg: Fixed code formatting

Answer 505305b66b8c02000203a072

4 votes

Permalink

You should be aware that W3schools is not the best source of JavaScript knowledge. Despite the name, they have no affiliation whatsoever with the W3 consortium (which defines the standards for the Web).

To answer your question: all the three notations below will work, but the first is the worst one, and the last is the best one:

for (x in object) {   }         // dirty, bad JavaScript

This variant (no var at all) creates a gobal variable. This should be avoided. Because if somewhere else in your code (or in JavaScript libraries you use) another global variable of the same name exists, your loop variable x will overwrite its value, potentially wreaking havoc.

for (var x in object) {   }     // clean and OK most of the time

This creates a local variable specifically for your current function / context. Most of the time for loops and for ... in loops use this notation to declare their counter variable on the fly.

var x; for (x in object) {   }  // slightly more efficient

This one equivalent to the previous, but now instead of declaring a variable again and again for every item in the loop (the var keyword declares it, meaning that it creates a new name in the current context’s namespace and reserves some memory), it is declared just once, and only its value gets updated on each loop run. The performance penalty you get when you use the second variant instead of the third is really tiny, but it can have some measurable effect if the loop is run many thousand times (especially if it is inside another loop that itself is run many times).

points
Submitted by Alex J
about 11 years

Answer 505210da8cff5d0002003f1c

0 votes

Permalink

I should have mentioned that I am using Firefox 15.0 for Mac.

points
Submitted by fmenot
about 11 years