JavaScript: The Good Parts

I've been a huge fan of Douglas Crockford and his articles about JavaScript for a long time. I often point people to his The World's Most Misunderstood Programming Language article when I hear them complaining about the language. It's taken me a couple of years to get around to reading his book, JavaScript: The Good Parts, but it exceeded all of my expectations.

Being an avid reader of his online stuff, and having watched various talks of his I knew the book would be well written and informative, but I thought it'd probably just repeat much of what I'd already read, without providing much new information or insights. To a certain extent this was true, the book does reiterate what's said in many of his online articles and talks, but the book is absolutely amazing for a different reason: The code examples.

The book is extremely succinct. There's no padding, and very little dialog to join one section to the next. There is a common thread thoughout the book though, and that's the code. Examples of good coding practices are repeated, and functions written in earlier chapters are often reused in later ones. So although the book appears to be presenting one feature at a time with a small code example you're actually building up more and more complex javascript applications, and the book ends with a full JSON parser!

Crockford's coding style seems to match his writing style: succinct and to the point. There's some really great code in the book, that I think even non-JavaScript developers could appreciate. Here's my favourite, from the chapter on regular expressions:

var parse_url = /^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/;
var url = '';

var result = parse_url.exec(url);
var names = ['url', 'scheme', 'slash', 'host', 'port', 'path', 'query', 'hash'];
var blanks = '       ';
var i;
for (i = 0; i < names.length; i += 1) {
    document.writeln(names[i] + ':' + blanks.substring(names[i].length), result[i]);

Which outputs:

scheme: http
slash:  //
port:   80
path:   goodparts
query:  q
hash:   fragment

I also love the explanations Crockford gives as to why he avoids using certain parts of JavaScript, and limits himself to a "good" subset of the language. He doesn't simply say "This is bad and you shouldn't use it", it's usually accompanied by a story about a time when Crockford had used that feature and got caught out, which is much more compelling.

I think it's fair to say that JavaScript: The Good Parts is one of my favourite programming books: It's succinct, packed full of great code examples and best practices for writing maintainable and bug free code. It's a fantastic JavaScript reference, but much of what the book talks about is relevant to programming in general. Highly recommended!

Posted on 18 Jul 2010
If you enjoyed reading this post you might want to follow @coderholic on twitter or browse though the full blog archive.