Geeks With Blogs
Liam McLennan

Javascript allows you to declare variables simply by assigning a value to an identify, in the same style as ruby:

myVar = "some text";

Good javascript developers know that this is a bad idea because undeclared variables are assigned to the global object, usually window, making myVar globally visible. So the above code is equivalent to:

window.myVar = "some text";

What I did not realise is that this applies to for loop initialisation as well.

for (i = 0; i < myArray.length; i += 1) {


// is equivalent to

for (window.i = 0; window.i < myArray.length; window.i += 1) {


Combine this with function calls nested inside of the for loops and you get some very strange behaviour, as the value of i is modified simultaneously by code in different scopes. The moral of the story is to ALWAYS declare javascript variables with the var keyword, even when intialising a for loop.

for (var i = 0; i < myArray.length; i += 1) {

Posted on Tuesday, March 9, 2010 8:56 PM | Back to top

Copyright © Liam McLennan | Powered by: