I recently found a great example of the importance of the var keyword and properly scoping your variables in javascript. In the best case, we should be coding in an object oriented way and utilizing closures to properly contain our code, but sometimes we run into some plain old javascript written the old fashioned (read: messy) way.
By omitting var, we are essentially declaring the variable in the global scope, which is most likely not something we want to be doing. A great example is when declaring an iterator variable for a loop. Without var, the iterator is exposed to any functions called within the loop. If that function also has a variable of the same name that is not locally scoped, you will find that upon completion of the called function, your iterator is suddenly way off.
// some (incorrect) loop calling a function
for(iterator=0; iterator<5; iterator++) {
child();
}
};
// This function can then mess with our iterator!
function child() {
iterator = 99;
}
This example shows how some code hidden away in a called function may inadvertently mess with your variables. It is only made worse when both caller and callee are disregarding scope by omitting var. The proper loop is then obvious:
By doing so, we ensure that no one else can accidentally mess with the internals of our code. This is an easy mistake to make, but fortunately not too difficult to identify and correct.