Skip to content
Advertisement

Preventing auto-creation of global variables in Javascript

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.

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement