Compilation © 2008, Martin Rinehart |
Contents
|
All naming conventions—capitalization and use of underscores—are self-descriptive:
|
| Shorthand | Title | Author | URL |
|---|---|---|---|
| Crockford | Code Conventions for the JavaScript Programming Language | Douglas Crockford | javascript.crockford.com/code.html |
| Nextapp | JavaScript Code Conventions | echo.nextapp.com/site/node/124 | |
| Amaran | Javascript Naming Conventions, Coding Guidelines and Best Practices | Rahul Amaram | http://rahul.amaram.name/blog/2007/04/13/ javascript-naming-conventions |
| Sakalos | Tutorial:Application Layout for Beginners | Jozef Sakalos | extjs.com/learn/ Tutorial:Application_Layout_for_Beginners |
| Murray | JavaScript Recommendations for AJAX Component Writers | Greg Murray | blueprints.dev.java.net/ bpcatalog/conventions/ javascript-recommendations.html |
| Komenda | (My) JavaScript Coding Guidelines and Standards | Klaus Komenda | www.klauskomenda.com/code/ my-javascript-coding-guidelines-and-standards/ |
| Michaux | How to structure your JavaScript code | Peter Michaux | ajaxian.com/archives/ how-to-structure-your-javascript-code |
| Dojo | Dojo Style Guide | dojotoolkit.org/developer/StyleGuide |
This paper is a compilation of the above eight convention documents. It is not a substitute for those documents. It omits, for one, the authors' arguments supporting their positions. For example, Crockford writes, "All of our JavaScript code is sent directly to the public. It should always be of publication quality." That is reduced here to "Crockford: JavaScript should be publication quality."
Dojo has conventions that "must" be followed and "should" be followed. These are included here as conventions. It also has conventions that you "may" or "can" follow. These are not included here.
Each source is cited for each convention. If a convention is attributed to Amaran, Sakalos: the other documents do not cover this point or they disagree and are covered immediately, such as, "Crockford: Lines 80 characters wide. Nextapp: Lines 132 characters wide."
|
top General File Objects Arrays Functions Other Objects Blocks Statements Expressions Variables Constants Comments |
Crockford: JavaScript should be publication quality.
Murray: Use JavaScript conventions. (Links to Dojo conventions document.) Use OO JavaScript. XML is good but JSON can be better. Dereference unused objects. Use care with closures. Design for internationalization.
Komenda: Use library methods for cross-browser code.
Dojo: Violating conventions is OK if the violation improves readability.
Dojo: Use lowercase, one word.
Crockford, Michaux, Dojo: Use blank lines to divide code into sections.
Michaux: Start sections with comment. Overall: namespace wrapper, then helper functions, constructors, private methods, mainline code, public methods, end namespace wrapper.
Sakalos: Start with JSDoc comment, then links to external library, namespace start, private variables, private functions, public functions, end namespace and end with eof comment.
<script src=filename.js> should be placed as late in the HTML body as possible.
Almost always use .js files.
Amaran: JavaScript inline w/HTML should be hidden from validator.
|
top General File Objects Arrays Functions Other Objects Blocks Statements Expressions Variables Constants Comments |
Amaran: Prefix with underscore, if private, 'g' or 'm' for global or member, 'a' (for array) and name in UpperAndLower form.
Komenda, Dojo: Use plural for collections: for (person in people).
[], not new Array().
Komenda: Use fast loop code: for (var i=0, len=arr.length; i < len; i++); Dojo: Variables initialized before loop are preferred over variables initialized in the loop.
Amaran: Use setAttr(), getAttr(), isAttr, doSomething.
Michaux: Use lowerAndUpper names.
Dojo: Use lowerAndUpper() for public methods. Use verb or verb phrase for methods ( getFish() ). Use get/set to access private fields. Use "is" prefix for boolean getter. UI widgets should be suffixed with type: leftComboBox.
Amaran, Dojo: Acronyms within names, only initial cap (getXml(), writeHtml() ).
function name([arg][, arg]...) {. If anonymous: function (args) {. Dojo: No space after anonymous function.
Murray: Function blocks not indented.
Komenda: Include JSDoc comments with @param and @return comments. @param should list allowed types.
setTimeout() and setInterval(). Avoid eval().
Crockford, Komenda: Do not use new Function().
Komenda: Use var YDOM = YAHOO.util.Dom; to minimize function lookup time. Every function should only do one thing.
Crockford, Amaran: Use iniitial capital letter for objects that will be instantiated with new.
Dojo: Use UpperAndLower.
Crockford: Do not start with _. Dojo: Use _lowerAndUpper() for private methods.
{}, not new Object().
Murray: Use object hierarchies.
|
top General File Objects Arrays Functions Other Objects Blocks Statements Expressions Variables Constants Comments |
Amaran: Indent two or four spaces.
Michaux: Indent two spaces.
Crockford, Komenda, Dojo: Open curly at end of line above block; close curly on line below block, exdented.
if (cond) {
// statement[s]
} else if {
// statement[s]
} else {
// statement[s]
}
Crockford, Nextapp: Always use blocks after if, for, etc.
|
top General File Objects Arrays Functions Other Objects Blocks Statements Expressions Variables Constants Comments |
while, do, for, switch.
Dojo Sample broken line shows breaks before binary operators. [Editor's note: Dojo bases its conventions on the Geosoft Java conventions. Sun's Java conventions specify breaks before binary operators. Other Java conventions, including Geosoft's, specifically disagree with Sun on this point.]
Crockford, Nextapp, Amaran: Simple statements (including array/object assignments) end with ';'.
Crockford, Komenda: One statement per line.
Dojo: No space after break, catch, continue, do, else, finally, for, if, return, switch, this, try, void, while, with.
Space after case, default, delete, in, instanceof, new, throw, typeof, var.
Space after function if named; no space if anonymous.
if(condition){ ). Dojo permits falling through switch cases.
Crockford: The following table is from Crockford. Your editor added the try statement in a Crockford-like format. Comments in the table are also from Crockford.
|
Crockford: Avoid it. Dojo: break and continue are acceptable.
|
|
|
|
|
|
|
|
Do not use parens around value. Expression must start on line with return keyword.
|
|
|
|
|
|
|
|
Do not use it. |
|
top General File Objects Arrays Functions Other Objects Blocks Statements Expressions Variables Constants Comments |
.) separated from their operands by one space. No space for unary operators except for word operators (typeof). Space after every comma. Space after colons.
Dojo: Shows an example formatted this way:
aVar = anObj.method(
expr1,
expr2,
expr3
);
The Dojo text calls attention to the position of the comma.
Dojo: Space after commas, semicolons in for loops. No space before semicolons, function parameter lists.
Crockford: Use === and !==, not == and !=. Use parens to separate binary and unary plus:foo + (+bar). Avoid the comma operator except for disciplined use in control part of for statements (comma operator, not comma list separator).
Komenda: Use object.property (not getAttribute(), setAttribute()) to access DOM object properties.
Dojo: Use temporary variables to avoid complex conditionals. if (normal case) {...} else (exceptional case) {...}.
Use named constants, not numbers in code.
|
top General File Objects Arrays Functions Other Objects Blocks Statements Expressions Variables Constants Comments |
Crockford: Do not start with _. Dojo: Use _lowerAndUpper for private variables, method arguments and local variables.
Amaran: Two-letter prefix preceding UpperAndLower name. 'g' or 'm' (global or member), then sString, nNumber, bBoolean, aArray or oObject. gsHelloMsg = 'Hello, world!';. Prefix 'privates' with underscore.
Michaux: Use lowerAndUppercase.
Komenda: Use UPPER_CASE for global variables.
Dojo: Use lowerAndUpper for public variables. Use "num" prefix or "count" suffix as appropriate. Use "i", "j", ... for iterators. Complement names: get/set, add/remove, create/destroy, start/stop, insert/delete, begin/end, etc. Avoid abbreviations. No negated booleans: isNotFish is unacceptable. Use "Exception" and "Error" suffixes when appropriate.
setFish(fish); // where fish's type = Fish
All names should be in English. Name length should vary directly with scope of variable.
getHandler(); // not getEventHandler();
MouseEventHandler // not MsEvtHdlr
events.mouse.Handler // not events.mouse.MouseEventHandler
MouseEventHandler // extends EventHandler
Crockford: Alphabetical order.
var.
Crockford: Minimal globals. No implied globals.
Nextapp, Sakalos, Komenda, Michaux: All globals should be in namespaces. (Not in his convention, but Crockford codes this way.)
Dojo: Unless undefined is intended, assign a value when declaring variables. Never have dual meanings. Keep variables alive for the shortest time possible.
|
top General File Objects Arrays Functions Other Objects Blocks Statements Expressions Variables Constants Comments |
var TokenTypes = {
ResWord:1,
INTEGER:2
}
Nextapp: String literals: double-quoted, not single.
Amaran: Single quotes for JavaScript literals, double quotes for HTML attribute values.
Komenda: Use single or double quotes, but be consistent.
|
top General File Objects Arrays Functions Other Objects Blocks Statements Expressions Variables Constants Comments |
Nextapp: Use JSDoc comments for API specs.
Komenda: Use JSDoc comments for modules, functions. Mark browser workarounds with JSDoc HACK comments. Use JSDoc TODO comments when more should be done.
Dojo: Tricky code should be rewritten, not commented. Comments should be in English. Comments should precede or be to the right of the code they reference. Comments should identify the type of elements in a collection. Comments should precede blocks of code. Comments should not be included for every single line of code. [Editor: Dojo uses a comment system like that found in JSDoc, but it is not JSDoc.]