I just spent some time debugging a problem that boiled down to forgetting to use the var
keyword in front of a new variable identifier, so Javascript was automatically creating that variable in the global scope. Is there any way to prevent this, or change the default behavior, without using a validator like JSLint?
Running a validator in between writing and executing Javascript code seems like a poor excuse for compiling, which is the step I'd usually rely on to catch this sort of thing.
I'm guessing the answer is a "no," so I'm looking into a JSLint Eclipse plugin as I post this.
ES5 strict mode prevents automatic creation of global variables, but it's probably going to be a year before there are any shipping browsers that recognise strict mode, so JSLint is probably your best bet until then :-/
Check this handy bookmarklet created by Remy Sharp, you can use it to check whether any variables have slipped out to the global namespace.
Not that I know of -- JS developers have historically been adverse to adding "seat belts" to the core language, so they've been implemented in external tools like JSLint instead. You might consider adding JSLint to your build/test process via it's Rhino version, and make the test suite fail if JSLint reports errors.
The answer is indeed no - but you could use the Eclipse plugin as you said, which can as far as I know run when saving etc., so it won't require additional steps.
IntelliJ IDEA is also able to spot undeclared variables. IntelliJ does it real-time as you type and can also analyze your codebase jslint-style. Probably some other alternatives too.
I made a bookmarklet some time ago to inspect and detect global variables.
alt text http://yura.thinkweb2.com/detect_global.png
It has some additional features (like filtering out Prototype.js or Google Analytics properties) too.
Install Firebug, and enable it on your site. It will complain each time you create a global without var
, as well as some other situations which you might or might not want to catch.
You can also do this using the about:config
option javascript.options.strict
, but since that's global it'll affect all the other sites you browse too.