always end a javascript statement with a semi-colon

Although it is optional, I recommend always ending javascript statements with colons.

A very good reason for this is that some packers (one, two) reduce the file size by removing excessive white-space – including carriage returns.

For example, the following code:

  var a=3
  var b=4

– will be packed to this:

var a=3 var b=4

The above line is nonsense. If semi-colons had been used, then the statements would still be parseable.

Beware of this gotcha: when you create a function dynamically, you must still place a semi-colon after the closing ‘}’.

For instance, this code:

  this.onreadystatechange=function(){
    return false;
  }
  return true;

– will not parse after being stripped of its carriage returns. You must rewrite it like this:

  this.onreadystatechange=function(){
    return false;
  };
  return true;

Oh – and for those people that complain that packed source is harder to read and maintain than non-packed – always keep a copy of the original code in a /source directory. Every JavaScript library that I know of uses this scheme, so it should be good enough for anyone.

1 Comments.

  1. » addEvent winner announced « klog - pingback on October 19, 2005 at 9:40 am

Trackbacks and Pingbacks:

%d bloggers like this: