Sneaky Javascript For Loop Bug
        Posted  
        
            by Liam McLennan
        on Geeks with Blogs
        
        See other posts from Geeks with Blogs
        
            or by Liam McLennan
        
        
        
        Published on Tue, 09 Mar 2010 20:56:54 GMT
        Indexed on 
            2010/03/11
            4:40 UTC
        
        
        Read the original article
        Hit count: 390
        
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) {
}© Geeks with Blogs or respective owner