Archive for the JavaScript Category

A pair of simple (but useful) code conventions in JavaScript

Posted in JavaScript, Programming on December 17, 2008 by rubayeet

Let’s suppose you are writing a large and complex piece of javascript code for building some client-side features in your web application. Or may be a javascript library that is going to be used by others(who knows… may be the next thing after ‘JQuery’?). The following two pieces of code convention will help you/users of your code greatly, if you guys are planning to have code compaction.

If you don’t know about code compaction, it is the act of compacting your javascript code. All the whitespace in the source files are removed,  all the large variable/function names are replaced by short single character ones. The resulting source file is hardly human readable but still machine readable. The overall benefit is smaller size of javascript source files, hence faster loading time of the web pages. Steve Souder recommends this in his outlined best practices for speeding up websites.  

1. Put an end to that statement by a ‘;’

Javascript allows you to end a statement without using a semi-colon(;). But you should not do so. Otherwise a non-semicolon-terminated statement will get packed together with the next statement(s) to a form single one and will produce an error.

/*the first statement will get mixed up with the second one*/
var bad  = 'this is not good' 
var good = 'this is okay';

2. Always use multi-line comment delimiters (even for single line comments)

Using single line comment delimiters(//) will comment out the next statement upon compaction. So always use multi-line ones (/*…*/) for commenting.

//the next statement will get commented out

var commented = 'does it matter?';

That’s the two of them. And in case if you are looking for tools to compact your JS codes, here’s a couple of them:

1. JSMIN By Douglas Crockford

2. Packer by Dean Edwards