Damn Comma

June 10th, 2011 Permalink

Few things in Javascript annoy me as frequently as does what I choose to call the damn comma. What is the damn comma, you ask?

var array = [
  "a",
  "b", // <---- this is
]

var object = {
  x: "x",
  y: "y", // <---- so is this
}

It's that trailing comma that would be perfectly legal in PHP or Python, but which forces you to take that tiny extra bit of care whenever you edit an array or an object in Javascript - which, let's face it, you are going to be doing fairly often. If I had a dime for ever time a Node.js script of mine failed in development because of the damn comma ... well, I'd have a lot of dimes.

I switch back and forth between Javascript and PHP development all the time, often on the same project, which only makes matters worse. So to reduce my general sense of frustration, I wrote and published the damncomma.js package. This is a forthrightly ridiculous hack on the Node.js module loader and JSON object that I would never use in a real application, but its existence makes me feel better about the state of the world. You can install it via NPM:

npm install damncomma

With damncomma.js installed, you can do things like write this script, and save it as damncommaTest.js:

exports.dcArray = [ "a", "b", ];
exports.dcObject = { x: "x", y: "y",  };

Then load and run that illegal Javascript without your code exploding, as the trailing damn commas are removed before they can upset the V8 engine:

var dc = require("damncomma");
dc.modules(true);

// Existing modules are unaffected by the presence of damncomma.
// Probably. Maybe. But you like uncertainty, right?
var path = require("path");
var fs = require("fs");

// Load up a test module with damn commas, show that it works.
var testModule = require("./damncommaTest.js");
console.log(testModule.dcArray);
console.log(testModule.dcObject);

One of the entertaining aspects of Javascript is that you have a great deal of freedom to monkey with near every fundamental object and function. So I can wander in and hijack module loading or JSON parsing in Node.js in a few lines of code. Given that, there really isn't anything other than convention to stop the formation of an industry of layered and formalized script preprocessing akin to the baroque fun and games that characterize the C and C++ languages. Nor should there be - but just because it is easy to write something like damncomma.js, or easy to bring C-style preprocessing to Javascript on the server doesn't mean that either is a good idea.

I leave it as an exercise to the reader to look at the trivial damncomma.js implementation code and imagine all the things that could go wrong in the blanket application of even a carefully considered regular expression to loaded files and JSON strings.