JavaScript Coding Conventions

Compilation © 2008, Martin Rinehart

 

Contents

Introduction
General
File
Objects
    Arrays
    Functions
    Other Objects
Blocks
Statements
Expressions
Variables
Constants
Comments
  All naming conventions—capitalization and use of underscores—are self-descriptive:
  • lowerAndUpper
  • UpperAndLower
  • UPPER_CASE
  • lower_case
 

Introduction

The following table summarizes "Results 1-10 of about 282,000" Google search results for "javascript code conventions", 10/29/2008 (less one duplicate, one broken link and an off-target book, plus Dojo:, another major convention document linked by Murray:). This table is in Google's order.

JavaScript Convention Documents
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

General

Crockford, Nextapp, Sakalos, Murray, Komenda, Michaux: The name is JavaScript. Amaran: The name is Javascript.

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.

File

Naming

Crockford: filename.js.

Dojo: Use lowercase, one word.

Formatting

Crockford: Lines 80 characters wide. Nextapp: Lines 132 characters wide.

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.

Documenting

Sakalos: Begin with JSDoc comment. End w/"end of file" comment.

Other

Crockford: <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

Objects

Arrays

Naming

Crockford: (See variable naming.)

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).

Other

Crockford. Nextapp, Komenda: Use [], 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.

Functions

Naming

Crockford: (See variable naming.)

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() ).

Formatting

Crockford: Declared before used. Spaces this way: function name([arg][, arg]...) {. If anonymous: function (args) {. Dojo: No space after anonymous function.

Murray: Function blocks not indented.

Documenting

Amaran: Every function begins with explanatory comment.

Komenda: Include JSDoc comments with @param and @return comments. @param should list allowed types.

Other

Crockford: Minimize global functions. Pass functions (not strings) to 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.

Other Objects

Naming

Crockford: (See variable naming.)

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.

Other

Crockford, Nextapp, Komenda: Use {}, not new Object().

Murray: Use object hierarchies.

top
General
File
Objects
    Arrays
    Functions
    Other Objects
Blocks
Statements
Expressions
Variables
Constants
Comments

Blocks

Formatting

Crockford, Nextapp, Sakalos, Komenda, Dojo: Indent four spaces (not tab). Dojo: Use tabs set to four spaces. Indent eight spaces.

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

Statements

Naming

Crockford: Only label while, do, for, switch.

Formatting

Crockford: Wide lines should be broken after an operator, preferably a comma. Indent continuation line 8 spaces.

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.

Other

Dojo: The following statement formats are from Crockford. Dojo also includes statement format conventions. They differ from Crockford in two ways. First, their blocks are indented eight spaces. Second, they use no horizontal spacing except when mandatory ( 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.

Statement Details

continue

Crockford: Avoid it. Dojo: break and continue are acceptable.

do


            do {
                statements
            } while (condition);

for


            for (init; condition; update) {
                statements
            }

            for (x in y) {
                // if x.hasOwnProperty()
                statements
            }

if


            // always use blocks
            if (condition) {
                statements
            } else if (condition) {
                statements
            } else {
                statements
            }

return

Do not use parens around value. Expression must start on line with return keyword.

switch


            switch (expr) {
            case expression:
                statements
                break return or throw; // never fall through
            default:
                statements
            }

try


            try {
                statements
            } catch(ex) {
                statements
            } finally {
                statements
            }

while


            while (condition) {
                statements
            }

with

Do not use it.

top
General
File
Objects
    Arrays
    Functions
    Other Objects
Blocks
Statements
Expressions
Variables
Constants
Comments

Expressions

Formatting

Crockford: Separate left parens by one space after keywords (including 'function'); no space after function names. Binary operators (except .) 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.

Other

Crockford: No assignments in condition parts. Dojo: No executable code in condition parts.

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

Variables

Naming

Crockford: No $, no \. Use only upper/lower English characters, digits and underbar. Most should start with a lower case letter.

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

Formatting

Crockford, Komenda: Declare all variables at top of function, one per line. Dojo: Declare variables in the smallest scope possible. Declare related variables of the same type in one statement.

Crockford: Alphabetical order.

Documenting

Crockford, Komenda: EOL comment on line where declared.

Other

Crockford, Komenda: Always declare with 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

Constants

Naming

Dojo: Use UPPER_CASE or UpperAndLower for constants. Crockford: Do not use UPPER_CASE for constants.

Formatting

Dojo: Constants should be within an enum-like object:

            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.

Other

Crockford, Dojo: Decimal constants must have at least one digit before the decimal point (use "0.5", not ".5"). Dojo: Decimal constants must have at least one digit after the decimal point ("1.0", not "1.").
top
General
File
Objects
    Arrays
    Functions
    Other Objects
Blocks
Statements
Expressions
Variables
Constants
Comments

Comments

Crockford: Generous and up-to-date. Do not repeat the code.

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.]

# # #