You can put your functions anywhere you like, but there are a few special things to note:
1. If you declare a "native function", you can put it anywhere. This is because of something called "function hoisting", which means that the Javascript engine automatically moves your functions to the top of the file in the execution engine when it is being run:
Code: Select all
//this is fine for the usage to come "before" the function definition
var value = doSomething(5);
function doSomething(val) {
return val + 10;
}
2. If you create a "function object", this is not the case. Function objects are not hoisted. Notice the difference in how the function is declared:
Code: Select all
//this is NOT ok!
var value = doSomething(5);
var doSomething = function(val) {
return val + 10;
}
3. The same rules as function objects apply when you are dealing with "methods", which are functions that are part of an object. This perhaps is what you are talking about, since this is the syntax you used in your post. You cannot typically define a function with a name and a colon unless it is inside of an object literal (the object literal in this case being called "myObj"):
Code: Select all
//this is also NOT ok!
var value = myObj.doSomething(5);
var myObj = {
stored: 10,
doSomething: function(val) {
return val + this.stored;
}
}
However, it is generally a best practice to keep your functions at or near the top, because function hoisting can be confusing for others trying to read your code if your file is particularly long. They may see the function being called, but have to go down hundreds more lines of code to actually see what it does.
At the end of the day, place your functions where they make the most sense to you. If they are methods inside of an object, you really don't have a lot of room to deal with. They will either go above fields (object variables) or below. People coming from different platforms have different practices, with most people coming from Java or .NET putting fields first, and then methods, and some people coming from C++ or others doing it reverse.