Difference between using var and not using var in JavaScript

You should always use the var keyword to declare variables. Why? Good coding practice should be enough of a reason in itself, but declaring a variable without the var keyword means it is declared in the global scope (a variable like this is called an "implied" global). Douglas Crockford recommends never using implied globals, and according to the Apple JavaScript Coding Guidelines:
Any variable created without the var keyword is created at the global scope and is not garbage collected when the function returns (because it doesn’t go out of scope), presenting the opportunity for a memory leak.
So, in short, always declare variables using the var keyword.

Comments