Skip to content


Subversion checkout URL

You can clone with
Download ZIP

Node.js code style

Irakli Nadareishvili edited this page · 16 revisions
Clone this wiki locally

Based on:


Line Length

Keep lines shorter than 80 characters. It's better for lines to be too short than to be too long. Break up long lists, objects, and other statements onto multiple lines.

Use Spaces to Disambiguate Parens

  • No space before ( when used to invoke a function
  • No space between a function name and a parameter list
  • One space between al other names and (


foo (bar);
if(a===0) { ... }
function foo (b) {...}
function(x) { ...}

Inline Comments

To keep line lengths short and improve readability, do not put comments on the same line as the code, rather put them on the line before


if (foo) { bar() } // This is just a demonstration


// This is just a demonstration:
if (foo) { bar() } 

Use the following format for comment blocks related to functions and files:

 * This is the base document model.  
exports = module.exports = function DocumentModel(payload) {


Two-spaces. Tabs look like hell in web browsers (and on github), and node uses 2 spaces, so that's that.

Curly Braces

Curly braces belong on the same line as the thing that necessitates them. Use curly braces even for single-line blocks (for "but, why", see: Douglass Crockford's explanation)


if (foo) bar();
while (foo)


if (foo) { bar(); }
while (foo) {

Comma First

Javascript errors on extra commas! If there is a list of things separated by commas, and it wraps across multiple lines, put the comma at the start of the next line, directly below the token that starts the list. Put the final token in the list on a line by itself. For example:

var magicWords = [ "abracadabra"
                 , "gesundheit"
                 , "ventrilo"
  , spells = { "fireball" : function () { setOnFire() }
             , "water" : function () { putOut() }
  , a = 1
  , b = "abc"
  , etc
  , somethingElse

This also means that we avoid using extra "var" declarations and group related variable declarations under one "var" keyword (as shown in the example above).

Separate Module Imports

The fact that we group variable declarations under one "var" keyword does not mean that all variable declarations must always be lumped-up under one "var" keyword. On the contrary, we require all module imports ("require" declarations) to be separated from other variable declarations. Furthermore, we require all local module imports (those we create) to be separated from official NPM module imports (those we get via NPM).


var storage     = require('../../storages')
  , httpCodes   = require('../../httpCodes')
  , _           = require('underscore')
  , lorem       = ipsum
  , foo         = bar;


// NPM modules
var _           = require('underscore')

// Local modules
var storage     = require('../../storages')
  , httpCodes   = require('../../httpCodes')

// Other variables
var lorem       = ipsum
  , foo         = bar;

Align Operators

Aligning equal signs and colons for a multi-line expression makes HUGE difference in code readability. We commit to making this happen. There're plugins for many text editors and IDEs to help formatting this way (e.g.: so: no excuses accepted.


var storage = require('../../storages')
  , httpCodes = require('../../httpCodes')
  , _ = require('underscore')
  , CONF = require('config')
  , parse = require('../../parseUtil');

  rel: "profile",
  type: "application/json"


var storage   = require('../../storages')
  , httpCodes = require('../../httpCodes')
  , _         = require('underscore')
  , CONF      = require('config')
  , parse     = require('../../parseUtil');

  rel  : "profile",
  type : "application/json"

Ternary Operator: Always Multiline


var description = (typeof fromDoc === "undefined") 
                  ? '' 
                  : fromDoc;

Long expressions

When using long expressions, make them multi-line to avoid longer-than-80-characters code lines. When possible the operator on the new line should go under the first operator AFTER the equal sign, rather than under the equal sign, to make things more readable. Obviously sometimes we only have one in which case operator should be indented by two spaces.


var pluginName = __dirname + '/Queue' + CONF.queue.use[0].toUpperCase() 
                           + CONF.queue.use.substr(1).toLowerCase() 
                           + 'somethingLongForDemo.js';
// or
var pluginName = '/QueueIsALongNameToMakeGoodDemoLoremIpsumDolor.sitAmet' 
                 + CONF.queue.use[0].toUpperCase(); 

For multi-line if statements, logical operators should be aligned under each other and under the opening braces, with any additional spacing that makes sense to improve readability (note how "typeof is indented from the opening braces in this case because it makes things more readable):

 if(  typeof data.Body.SendMessageResponse === "undefined"
   || typeof data.Body.SendMessageResponse.SendMessageResult === "undefined"
   || typeof data.Body.SendMessageResponse.SendMessageResult.MD5OfMessageBody === "undefined"
   || data.Body.SendMessageResponse.SendMessageResult.MD5OfMessageBody !== md5) {

Proper use of this is using self

Using this is dangerous! It can change scope in closures without your recognizing the scope change, so always, always assign:

var self = this;

and use self where you would normally use this, even if you know what you are doing. Somebody altering code down the road may not notice your intent and introduce a nasty bug.

Use of semicolons (;)

Semicolons should always be used to terminate statements. So instead of this:

var someMethod = function() {
  var someVariable = null

do this:

var someMethod = function() {
  var someVariable = null;

Code Flow

Auto-mounting Modules

Code organization should follow approach of auto-mounting modules advocated by TJ. For an example please see: NodeBootstrap's Example Module

Use Named Closures

Use named callback functions, please. You do not have to name those (esp. in trivial cases), but naming makes stack traces a lot easier to read.

Sync vs Async

Always use (and write) the asynchronous/non-blocking versions of things when you are dealing with I/O bound operations! Remember: for async functions returning a value makes no sense. Async functions should accept a callback parameter.

Callbacks in Async Flow

Callbacks of async functions should have err object as the first parameter. Common syntax:

var someCallback = function(err, data) {
  // ...

Use Errors Objects

Always create a new Error object with your message. Don't just return a string message to the callback. Stack traces are handy. Pass null instead of err if there is no error.

Let Error objects bubble + log if can not recover.

Rule of thumb: if your function ends with an invocation of a callback, then in 99% of cases it is a good idea to not try handle errors yourself and instead let them bubble up by handling errors as follows:

if (err) {  // not (err!==null)

In a web request, typically you want your errors to bubble-up all the way to a controller so the controller can report the error to the API user.

If your function does not continue with a callback, or if you are certain (really?) that upper-level function should not see your error (again: really?), or if you are already in the callback then whenever you finally handle the error use a pattern that looks like the following piece of code:

if (err) util.log("ERROR deleting message: " + + " from message queue: \n" + util.inspect(err));

Obviously you may also try some recovery steps, but at the very least every error should get logged at some point or another! DO NOT ever just let an error remain ignored!


Do not use console.log or console.dir! Use util.log() instead since it displays timestamp, or metalogger for more flexible logging.

Case, naming, etc.

functions, methods, members, instances

Use lowerCamelCase for multiword identifiers when they refer to objects, functions, methods, members, or anything not specified in this section.


Javascript does not have a notion of class as you would think of a class in a classical OO language. "new" keyword in Javascript is a syntactic hat tip to Java developers that is alien. Read more here: or Douglass Crockford's posts: and

If you are stubborn enough to still want to use "classes" in Javascript, use UpperCamelCase for class names (things that you'd pass to "new").

Filenames and config keys

Use all-lower-hyphen-css-case for multiword filenames and config keys.


Use CAPS_SNAKE_CASE for constants, things that should never change and are rarely used.

Function delcarations

Always declare functions as variables:

var functionName = function() { 
   // ...

Throw-away functions

Use a single uppercase letter for function names where the function would normally be anonymous, but needs to call itself recursively. It makes it clear that it's a "throwaway" function.

null, undefined, false, 0

Boolean variables and functions should always be either true or false. Don't set it to 0 unless it's supposed to be a number.

When something is intentionally missing or removed, set it to null. Don't set things to undefined. Reserve that value to mean "not yet set to anything." Boolean objects are verboten!

Something went wrong with that request. Please try again.