Can this be done either via writing some code to intercept the global scope default declaration or via a setting within the javascript engine itself which each program or function has access to?
What I mean is if I could, at the top of the program (or function), tell the javascript engine to use local scope for undeclared variables instead of global scope... then, when the javascript engine compiles each function, it would declare them in local scope.
I understand if you want to declare a variable outside of the current scope, that should be done explicitly since no one knows where you want it declared, but I think defaulting to global scope leaves too much room for error and forces too much typing of var statements in each function, so I'd like to change the default in my programs if that's possible.
My primary purpose is to avoid having to type the list of local variables in a var statement at the top of every function, and to avoid the maintenance of keeping this list in sync with the local variables as I'm using them within a function. Not allowing a global scope default also reduces the risk of errors.
I would never want undeclared variables to end up in any higher scope than the scope in which they are first used. There is no value in having them default to global scope that I can see.
I know I can explicity declare variables in the current scope (or the global scope), but would like to avoid doing so and use a more useful default than the global scope default built into javascript.
I also know I can use "use strict" to force all variables to be declared explicitly. Not wanting to debate the right or wrong of it, but just asking if there is any way to change the default to local scope instead of global scope for a given function.
No, Javascript behaves the way it does, there's no switch to flip to turn its variable declaration rules on its head.
'use strict'
is an option you can employ to help you catch problems more easily, but it doesn't change the rules.
What you want is a different language; for example CoffeeScript, a Javascript preprocessor which, among other things, happens to solve this variable declaration issue explicitly.