I have a JavaScript snippet with a recursive function call:
(function () {
"use strict";
var recurse = function (x) {
if (x <= 0) {
return;
}
return recurse(x - 1);
};
recurse(3);
}());
This does nothing but call itself a few times, but it runs.
Pasting the above into JSLint gives me this error:
'recurse' is out of scope.
However, if I paste in the following snippet, (using a function declaration instead of var):
(function () {
"use strict";
function recurse(x) {
if (x <= 0) {
return;
}
return recurse(x - 1);
}
recurse(3);
}());
JSLint loves it, no errors.
I know that the goal of JSLint is to prevent bugs in JavaScript code. Does anyone know why JSLint thinks the first one is bad JavaScript? What bug am I preventing by not making a recursive call in the first way?
EDIT: To any future visitors to this question: Neither of these JavaScript snippets throw any errors in the latest version of JSLint.
recurse
has the valueundefined
. This is not a problem, of course, because by the time you actually call your function,recurse
is defined.var recurse;
and thenrecurse = function...
that makes the warning go away without changing the situation I described above at all. The real issue is that JSLint doesn't registerrecurse
as being in-scope until the entirevar recurse = ...
expression is evaluated (but the left-hand side along ought to be enough for it to know that).