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

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


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s