This forum is now read-only. Please use our new forums! Go to forums
"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
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).
Popular free courses
- Free Course
Learn SQL
In this SQL course, you'll learn how to manage large datasets and analyze real data using the standard data management language.Beginner friendly,4 LessonsLanguage Fluency - Free Course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner friendly,11 LessonsLanguage Fluency - Free Course
Learn HTML
Start at the beginning by learning HTML basics — an important foundation for building and editing web pages.Beginner friendly,6 LessonsLanguage Fluency