I was thinking about the javascript programming style, and I was wondering if it makes sense to add some syntactic sugar to protect against the easily made mistake of using an implicit global, i.e.:
var OuterFunction = function() {
In this example, the counter suddenly becomes a global variable, and the other is locally bound to OuterFunction instances.
By "declaring" a void variable fixed with the closure, you get a free statement, much like any other code that uses counter without its purpose.
this.resetCounter = function () { void counter; // this will throw an Error if counter is not in scope. counter = 0; return this; };
Edit : as jleedev pointed out , just using the variable name itself seems to check if it exists, i.e.
this.resetCounter = function () { counter; counter = 0; return this; };
will work just as well.
I see the following benefits:
- This is a short description.
- This appears to be a variable declaration in which it resides.
- Edited to add . If done sequentially, it is very simple to check the syntax (meat or program) to detect errors of this kind.
On the other hand:
- This is confusing. The code actually does nothing.
- Future translators may consider this as meaningless, painless code and optimize it.
Are there any aspects that I'm missing? Is this a stupid idea, or is it at least somewhat justified?
Question asker Edit : This should be a community wiki question, but I donβt see a checkbox to change it to this. I vaguely remember that there is one.
Edited for great stupidity : of course, += tries to get the value of the expression before the increment. Therefore, we renamed the example to resetCounter , not incrementCounter , so that it makes little sense.