Chris S Chris S - 1 year ago 85
Javascript Question

JSLint: Using a function before it's defined error

I'm using JSLint to verify most of my external Javascript files, but the largest amount of errors I'm getting is from functions being used before they're defined.

Is this really an issue I should worry about?

It seems Firefox, IE7 and Chrome don't care. Functions like the popular

(which I use often) normally stick at the top as that makes sense to me (I like to pretend it's analogous to
) will, according to JSLint, need to be pushed to the bottom of the file.

Answer Source

If you declare functions using the function keyword, you can use them before they're declared. However, if you declare a function via another method (such as using a function expression or the Function constructor), you have to declare the function before you use it. See this page on the Mozilla Developer Network for more information.

Assuming you declare all your functions with the function keyword, I think it becomes a programming-style question. Personally, I prefer to structure my functions in a way that seems logical and makes the code as readable as possible. For example, like you, I'd put an init function at the top, because it's where everything starts from.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download