I just tried throwing my nasty variable declarations at JSLint (using its undefined variable detection):
function assign()
{
i = 10;
var i;
}
assign();
alert(typeof i);
It gave back the following errors:
- Problem at line 4 character 8: Var i was used before it was declared.
- Problem at line 4 character 8: Identifier ‘i’ already declared as global
I assume the first error message is only a stylistic preference, like so many other lint warnings, but I would enjoy like to hear Crockford’s explanation. I was a bit surprised by the second warning, because that’s not the case.
I then tried the following code:
function foo() {
return bar();
function bar() {
return 10;
}
}
JavaScript Lint does not handle this very well at all, reporting that that foo doesn’t always return a value and that bar is unreachable code, neither of which are true. JSLint simply reports, “Inner functions should be listed at the top of the outer function”, sidestepping the issue entirely.
I’m not sure whether its worth the cost to solve these problems completely, since the purpose of a lint (for me) is more pragmatic than idealistic. But it’s no wonder developers are confused if they’re been getting misleading warnings from both lints. If there’s a cost-effective way to improve it, I’ll do that.
Update: Crockford defends these warnings on the basis that it makes code easier to read and understand.
Interesting issues. Are all the inner functions available at runtime? I never tried to rearrange function declarations…
Btw, I finally had a go at the ‘dynamic element creation’ script. I had some issues while accessing object properties:
var a={href:"http://rolandog.com",title:"My Page",style:"text-decoration:none;"};alert(a[1]); //undefined
alert(a['title']); //My Page
alert(a.title); //My Page
I read somewhere that from Javascript 1.1 and after, object’s properties aren’t accessible by an index (only if the property’s name itself is an integer).
Comment by rolandog [Visitor] — July 18, 2006 @ 11:31 pm
Yes, all the inner functions are available at runtime.
I wasn’t aware that JavaScript ever allowed object property lookups by an index, though–going off on a tangent–you could emulate that with a function that uses a “for-var-in”. For example:
Accessing it as an array seems a lot better than using index lookups on the object, since there’s no ambiguity regarding what the indices mean. But I’m not quite sure what I’d use this for.
Comment by Matthias Miller [Member] — July 19, 2006 @ 5:05 am