JavaScript Fun!

I was recently working with JavaScript and ran into some weird things I hadn't ran into before.  While I'm sure the JavaScript masters of the world already know all about this stuff, hopefully this post can keep others from pulling out too much hair.  The first one deals with scoping:

If you don’t explicitly var an object, that object is declared globally.  The code will typically not fail, however, it will give you odd behavior.  This becomes an issue if you have the following:

 function Loop1(){
        for(x = 0; x < 10; x++){
            Loop2();
            alert(x);
        }
    }
   
    function Loop2(){
        for(x = 0; x < 10; x++){
            //do work here
        }
    }

You would expect the alert to occur 10 times, however, since the x declared in the first for loop does not have var in front of it, the variable is global.  When Loop2 is called, the loop increments x to 10 causing the for loop in Loop1 to only occur 1 time.  To correct this code, change the for loops to:
for(var x = 0; x < 10; x++)

The other issue deals with naming of objects and functions.  If you're developing everything it's no big deal as you will typically know what the ID's will be on the client as well as the names of JavaScript functions, but if you're leveraging someone's JavaScript library, this can become more interesting.   The error you get in Internet Explorer is "Object doesn't support this property or method".  The following line will reproduce the behavior, but imagine if you had a page with 50 controls and the function name that matches is in a JavaScript file you didn't write:

 <input type="button" id="AbortCallback" value="Abort" onclick="AbortCallback()" />