I'm trying to understand why JSLint complains about an implied global variable in the following example:
var TEST = (function () {
var count = 0;
function get_count() {
return add_one();
}
function add_one() {
count += 1;
return count;
}
return {
get_count: get_count
};
}());
Running this through JSLint gives the error:
Problem at line 5 character 12: 'add_one' is not defined.
As well as saying:
Implied global: add_one 5
If you move the add_one()
function before the get_count()
function the error goes away. However with the code as it is above, it doesn't produce any errors when you run it in the browser. Can anyone explain why JSLint is complaining?
Thanks!
Matt
This is because JSLint
uses a Pratt Parser, a top-down parser, not a full-blown JavaScript interpreter.
If it were truly interpreted, then it wouldn't give you that error.
add_one
is an implied global because the parser didn't come across that variable yet, so it assumes that your surrounding code will have that variable.
But, if you flip it around, then the parser has already came across the add_one
variable and it's all peaches and cream :-)
By the way, I noticed a small typo in your closing function line:
}());
should be })();
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With