Thursday, January 22, 2009

Finally, I found a good book on JavaScript!

For some years I have been looking for a book on JavaScript that would explain the language to someone who already knows programming. But all I have seen until recently are books for beginners or books that talk a lot about web programming, web browsers, DOM, XML, HTML etc, or books that explain all the different versions of JavaScript implemented in different browsers (many of these books have 1000 pages or more).

The book I read is a 180 page book called JavaScript: The Good Parts by Douglas Crockford. The idea of the book is: JavaScript is a messy language but here is a subset and some best practices how to use JavaScript in a manageable way. And that is done on 100 pages (the rest are interesting appendices). I read it last week on a flight and it was a kind of eye opener for me.

I finally understood that the object system of JavaScript is not class based like in C++/Java/Python/Ruby but it is prototype based like in Self/Perl/Lua. This prototype based approach is not supported by a special syntax. There are many ways of creating and dealing with objects. But be book makes some suggestions and explains some best practices for creating objects.

The other eye opener was how closures can be used to build objects with private information.

An interesting design decision of JavaScript is that there is essentially one data structure, called Object, with string keys and any object as value. It can be used as hash map, array or object. Even functions are objects and you can associate information with them or add methods to one or all functions.

If an object is used as array, the index is converted to a string key -- I find this very strange -- but it seems to work. The array.lenght attribute is defined as the "largest integer property name plus one", which means it looks for string keys that look like positive integers and takes biggest one, provided it is less than 4294967295.

If you want to learn JavaScript as a language I would highly suggest to read JavaScript: The Good Parts. After you finished the book, you might not be able to read any bad JavaScript programm, but you might be able to write your own "clean" scripts. I really like that approach.

If you are interested in E4, knowing JavaScript might be useful, because E4 will be scriptable with JavaScript.

1 comment: