It should be of no surprise that following conventions while programming can help foster maintainable and reusable code. This should be a simple concept to grasp, since using agreed upon rules up front for any form of communication will typically add clarity. Communication through programming is no different. So it makes sense that most programming languages use conventions to help clarify the meaning of the code. This is not only for your benefit, but also for the benefit of those who are going to be interpreting, reusing, and adding functionality to your Web site or Web application.
In this article we are going to look at some JavaScript coding conventions. Of course, this is not the be-all and end-all list of JavaScript coding conventions. In fact, the specifics of each convention should be a secondary concern in comparison to having a convention at all, and actually being able to follow it. With that said, below are the conventions I find to be an essential complement to writing JavaScript.
Keep JavaScript External - This convention is rather broad as it pertains to Unobtrusive JavaScript techniques. In general, the idea is that JavaScript should be written and maintained in an external file (yes, this includes events too), separate from the (x)HTML pages, by using the script element with the accompanying "src" attribute, which then links the JavaScript file to the page.
CamelCase Naming - Similar to built-in JavaScript methods (e.g. - getElementById), identifiers should start with a lower case letter, and the first letter of each subsequent new word should be uppercase. The one exception to this rule is when defining a class. When defining a class, the identifier should start with an uppercase letter, and the first letter of each subsequent new word should be uppercase. Additionally, when creating identifiers it is a good idea to think of classes as nouns (e.g. - Rectangle) and methods/functions as verbs (e.g. - getRectangleSize).
Avoid Underscores - Underscores should not be used in identifiers. However, private members of a class are often designated by starting the identifier with an underscore. Personally, I think this should be the only exception to the rule.
Use Spaces - I don't think there is a hard and fast rule on this one. I have a personal preference, but instead of specifying how spaces should be used in each scenario, I suggest that a space be used after a comma or semicolon, and before and after the assignment (=) operator. Obviously spaces must always be used with certain operators (e.g. - typeof, in, delete, void, new, instanceof). Remember that while JavaScript has some rules, it is considered a loosely typed language, and therefore, ignores tabs and white space. This is why it is possible to "minify" JavaScript code.