views:

173

answers:

6

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.

+5  A: 

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 :-/

olliej
+2  A: 

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.

John Millikin
+1  A: 

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.

Jani Hartikainen
+3  A: 

Check this handy bookmarklet created by Remy Sharp, you can use it to check whether any variables have slipped out to the global namespace.

CMS
A: 

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.

bobince
I already have Firebug and it didn't complain.
Matt Ball
You do have to make sure to enable it including the Script tab, as you would when doing script debugging; it doesn't interfere on its own.
bobince
+1  A: 
kangax