JavaScript Coding Style

My own personal guide.

A coding style is an agreement with yourself and the people involved in a codebase, to keep consistency on a project.

Having fixed rules on your code writing format helps a lot in order to have more readable & managed code, and code anyone can edit and feel right at home when doing so.


What coding style should you follow? There are a quite a few of them aroud, here are the 2 most common ones in the Javascript world:

Google Javascript Style Guide Crockford's Code Conventions for the JavaScript Programming Language Principles of Writing Consistent, Idiomatic JavaScript

In general, be consistent: if you edit code of a project, read the source and use the local style of that project. When starting a new project, your own personal style will be your own take. My own take on this subject is:

Indentation: use spaces instead of tabs, indent using 2 spaces.

Line length: use the line length you need. There's no real need to cut lines at 80 chars if that complicates your code.

Comments: use line comments inline in your code. Use block comments only to document. Don't leave old code commented, "just in case" it will be useful later. Keep only the code you need now, version control/your notes app is meant for this.

Don't add comments that don't help understand what the code is doing. If the code is self-explaining through the use of good variable and function naming, and JSDoc function comments, don't add a comment.

Variable declarations: declare all variables you use, to avoid polluting the global object. If a variable is used without being first declared with var, in addition, makes it hard to identify the scope it lives in. Declare all variables on top of the function scope they are defined in.

Constants: declare all constants in CAPS. Use _ to separate words in a VARIABLE_NAME. Use the @const annotation in the JSDoc if the type of the constant is not a primitive value (e.g. it's an object). Never use const as it's not supported by IE.

Function declarations: declare all functions before using them. Use the var statement to declare inner functions. No space should be between the function name and the parenthesis opening.

function test(a, b) {
  return a + b;
}

var myFunc = function(a, b) {
  return a + b;
}; //notice the semicolon

Feel free to use nested functions to hide helper functions to the rest of the code.

Never declare a function inside a block. It's not part of ECMAScript and there's no block scope, so all functions are moved to the beginning of the function scope when the code is executed.

Names: function names, variable names and method names always start with a lowercase letter (unless you identify them as private, read below), and are camelCased. Only constructor functions and "class names" should start capitalized. If you use a framework that requires specific conventions, change your habits accordingly. File names should all be lowercase, with words separated by -.

Private variables: use _ as the first character of a variable as a convention to treat it as a private variable. It's a practice not encouraged by some, but to be private a variable has to be declared in an object constructor (not in the prototype), it affects performance as every object carries that variable in its memory footprint. A sort of convention over configuration.

Statements: put only a statement per line. Every statement must end with ;. Don't rely on implicit insertion of semicolons as it's a sure source of bugs, especially in variable assignments (like illustrated above in the var myFunc assignment).

Statement labels: avoid statement labels. Just use them in loops (while, do, for) and in switch.

Statement-specific formats and rules:

if

if (condition) {
  statements
}

if (condition) {
  statements
} else {
  statements
}

if (condition) {
  statements
} else if (condition) {
  statements
} else {
  statements
}

for

Always initialize the length in the initialization to cache it, don't insert it in the condition.

Avoid using for in except with used in conjunction with .hasOwnProperty().

for (initialization; condition; update) {
  statements
}

while

while (condition) {
  statements
}

do

do {
  statements
} while (condition);

switch

switch (expression) {
  case expression:
    statements
  default:
    statements
}

try

try {
  statements
} catch (variable) {
  statements
}

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

Whitespace: use whitespace wisely to improve readability: put a whitespace after a keyword followed by a (; before & after a binary operation (+, -, /, *, &&..); inside the for statement, after each ; to separate each part of the statement; after each ,.

New lines: use new lines to separate blocks of code that perform logically related operations.

Quotes favor single quotes ' instead of double quotes ". Double quotes are a standard in HTML attributes, so using single quotes helps remove problems when dealing with HTML strings.

Visibility: encouraged the use of JSDoc annotations such as @private, @protected. They can be used by compilers such as the Closure Compiler to detect problems.

JSDoc: in addition to the visibility directives, you can use JSDoc to document the argument types of a method / function, like @param {Object} value A value.

Posted on Jan 11 2014
Written by Flavio Copes