JavaScript and Semicolons

Did you realize that semicolons are optional in JavaScript? I have to admit ignorance until just a few weeks ago – and I’ve been programming JavaScript on and off for seven years. Naturally, when I learned this I went and stripped all the optional semicolons from my code (well, it seemed like a good way to kill a few minutes at the time). It was a bit jarring to see a curly brace language without semicolons. See for yourself1:

function(testName) start
{
  if (!this.log) return;
  this.testName = testName;
  this.lastLogLine = document.createElement('tr');
  this.statusCell = document.createElement('td');
  this.nameCell = document.createElement('td');
  this.nameCell.appendChild(document.createTextNode(testName));
  this.messageCell = document.createElement('td');
  this.lastLogLine.appendChild(this.statusCell);
  this.lastLogLine.appendChild(this.nameCell);
  this.lastLogLine.appendChild(this.messageCell);
  this.loglines.appendChild(this.lastLogLine);
}

Versus:

function(testName) start
{
  if (!this.log) return
  this.testName = testName
  this.lastLogLine = document.createElement('tr')
  this.statusCell = document.createElement('td')
  this.nameCell = document.createElement('td')
  this.nameCell.appendChild(document.createTextNode(testName))
  this.messageCell = document.createElement('td')
  this.lastLogLine.appendChild(this.statusCell)
  this.lastLogLine.appendChild(this.nameCell)
  this.lastLogLine.appendChild(this.messageCell)
  this.loglines.appendChild(this.lastLogLine)
}

It also took a few days to get out of the semicolon habit – although I
still mistakenly put one in here and there (or more commonly name something
like_this instead of likeThis).

So is it worth it? I think so. I fall squarely in the camp that believes
syntax matters – the less of it the better. In fact, I think sparse syntax
plays a significant part in Python’s and Ruby’s popularity. Granted this change isn’t much – but
every little bit counts. Less syntax means less code which means faster
comprehension.

1Do you know which library this code comes from?
Its from unittest.js in script.aculo.us.

Leave a Reply

Your email address will not be published. Required fields are marked *

Top