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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
The call to
foo()will alertundefinedbecause x does not yet have a value whenfoo()is called, but you will notice thatfoocan 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.