The Javascript tutorial I follow always defines before using, but my PHP book always defines at the end, and in fact points out that this is considered good practice.
Is there a reason to do it one way or the other?
The Javascript tutorial I follow always defines before using, but my PHP book always defines at the end, and in fact points out that this is considered good practice.
Is there a reason to do it one way or the other?
If you have inline code executing (e.g. executing as it is loaded), then global variables must be defined before the code that uses them.
Functions can be defined in whatever order you think makes the code the most tidy and easiest to read.
For example, in this code:
foo();
function foo() {
alert(x);
}
var x = 4;
The call to foo()
will alert undefined
because x does not yet have a value when foo()
is called, but you will notice that foo
can be called in code that appears before the function definition because all functions are loaded before any code is actually executed.
As for a best practice, I think it makes sense to organize your code in the best way you can find that puts modules of related functionality together, but the order is not generally material. I trust you realize that javascript doesn't have anything that is actually a class. It can use function objects and prototypes to simulate some class-like behavior that other languages have, but it doesn't really have classes as it's objects are based on prototypes, not classes.