Reputation: 3085
Very quick question as I am having some kind of strange bugs and I can't find any documentation on this. Does order in which functions are defined in a file matter?
For example:
function a() {
b(); //defined below the current function
}
function b() {
//do something
}
Is it considered proper or do I have to mind the order?
Upvotes: 1
Views: 186
Reputation: 1506
Due to variable hoisting, "var statements and function declarations will be moved to the top of their enclosing scope" [1].
This can cause gotchas at times, but as long as the file containing the function is loaded, the order shouldn't matter.
[1] http://bonsaiden.github.io/JavaScript-Garden/#function.scopes, http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html
Upvotes: 5
Reputation: 28578
No, it does not matter, where function is. It can be at top of file, at bottom of file even in another file. what matter is existence.
Once JavaScript is loaded it will treated as single file or script; that is the reason you may not have function with same signature even on two different script file using on same page.
a();
c();
function a() {
b(); //defined below the current function
}
function b() {
alert("called b");
}
function c() {
b();//defined above the current function
}
Upvotes: 1
Reputation: 7416
The problem you're running into is variable hoisting. Read more about that here
It is considered improper to do that according to Crockford's JSLint. However, it shouldn't matter as long as you are defining the functions in that manner. For example, your code will work, but something like
function a(){
b();
}
function b(){
//do something
}
will work, but
function a(){
b();
}
var b=function(){//do something};
will not work.
So basically, if everything is loaded before you call it, you should be fine. Consider wrapping it in a $("window").load()
Upvotes: 2
Reputation: 2682
In JavaScript, it doesn't matter in what order functions are created as long as the called function exists.
Upvotes: 3