JavaScript Syntax – Why Do Node Packages Put a Comma on a Newline?

javascriptnode.jssyntax

I'm learning node.js and am trying out Express. My first app had this code:

var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path');

Reading through the mongoose tutorial gives me this:

var mongoose = require('mongoose')
  , db = mongoose.createConnection('localhost', 'test');

On strict mode, JSHint gives me

app.js: line 6, col 32, Bad line breaking before ','.

Which shows that I'm not the only one out there who's bugged by this syntax.

Is there any reason to declare vars this way instead of adding the comma at the end of the line?

Best Answer

I've heard it's called NPM style "comma-first" rule. Example from the doc:

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

The doc doesn't state the motivation behind this coding style, but I guess it's to prevent dumb syntax errors from placing an excessive comma at the end of a comma-separated list, and to alleviate the mental tax it places on you from trying to get that part of the syntax right.

Also note that NPM style recommends "not to use semicolons". If you adopt this style, you're also doing away with the semicolon that fills the final position of a var statement, making it tempting to place a comma there instead.

As for the JSHint error, there's a switch to allow comma-first style line breaks.

Related Topic