Book Review: Eloquent JavaScript by Marijn Haverbeke

This is the first in an occasional series of reviews of upcoming books. Please send drafts, sample chapters etc to anguscroll at gmail dot com

Title: Eloquent JavaScript
Author: Marijn Haverbeke
Publisher: No Starch Press
Release Date: November/December 2010

Here’s something to try. Go into your favorite bookstore (remember those?), head for the JavaScript section, take out a book you haven’t read and open it at random. Or just google “JavaScript array” or “JavaScript variable”. Either way there is a high probability you will encounter garbage. Crockford is right, JavaScript is indeed The World’s Most Misunderstood Programming Language™, yet its also one of the most popular and it’s crying out for decent literature.

All the more reason to celebrate the upcoming hard copy version of Eloquent JavaScript. The title was originally released as an interactive tutorial in digital format complete with an impressive cross-browser console. Ironically (and somewhat irresponsibly) I printed out a hard copy and it became my bedtime reading for the next month or so. I was immediately drawn to the clarity and wit of Haverbeke’s writing and the refreshing absence of condescension or arrogance (he’s on our side!). Best of all, I’d stumbled across that rare breed of author who really gets JavaScript, who understands JavaScript’s uniqueness and embraces it. I was an instant fan.

“There are those who will say terrible things about JavaScript. Many of these things are true. When I was for the first time required to write something in JavaScript, I quickly came to despise the language. It would accept almost anything I typed, but interpret it in a way that was completely different from what I meant. This had a lot to do with the fact that I did not have a clue what I was doing, but there is also a real issue here: JavaScript is ridiculously liberal in what it allows. The idea behind this design was that it would make programming in JavaScript easier for beginners. In actuality, it mostly makes finding problems in your programs harder, because the system will not point them out to you.

However, the flexibility of the language is also an advantage. It leaves space for a lot of techniques that are impossible in more rigid languages, and it can be used to overcome some of JavaScript’s shortcomings. After learning it properly, and working with it for a while, I have really learned to like this language.”

Eloquent JavaScript does not assume the reader is a JavaScript expert (in fact anyone with a web browser and a reasonable aptitude for software can profit from this book, no matter what their background). All Haverbeke demands is an eagerness to learn and a willingness to interact. Paradoxically there is plenty here for the seasoned JavaScript practitioner too. Haverbeke reconstructs familiar concepts (objects, arrays, functions, closures) from base principles and in doing so invites a new and clearer perspective.

The first two chapters introduce (or reintroduce) the language. Haverbeke’s approach is appealingly straightforward. He takes us on a seamless journey from the generic computer program to a decent understanding of JavaScript’s value types and control flow in just a few, very readable pages.

“Inside the computer’s world, there is only data. That which is not data, does not exist. Although all data is in essence just a sequence of bits, and is thus fundamentally alike, every piece of data plays its own role. In JavaScript’s system, most of this data is neatly separated into things called values. Every value has a type, which determines the kind of role it can play. There are six basic types of values: Numbers, strings, booleans, objects, functions, and undefined values.”

Next comes chapters on Functions, Objects and Arrays. Once again the writing is characterized by clear, holistic explanations. The reader is never left feeling they were supposed to know about some critical point that was glossed over. We get the why as well as the how. And the how is developed slowly and logically, with examples that build on one another. One small complaint: The lengthy saga of crazy aunt Emily’s cats which serves as both example and exercise gets a little tedious after a while – this is probably the only section that more advanced developers might want to skip.

There’s a succinct chapter on Errors (including a nice perspective on try/catch: “Most programmers consider exceptions purely an error-handling mechanism. In essence, though, they are just another way of influencing the control flow of a program”) then we are into my favorite chapter: Functional Programming. I’ve read and re-read this section many times. Its clear that Haverbeke has more than a passing interest in the topic and his passion translates into one of the most readable and insightful accounts of both the rationale and methodology of functional JavaScript.

“When writing a program, it is easy to get sidetracked into small details at every point. You come across some little issue, and you deal with it, and then proceed to the next little problem, and so on. This makes the code read like a grandmother’s tale.

Yes, dear, to make pea soup you will need split peas, the dry kind. And you have to soak them at least for a night, or you will have to cook them for hours and hours. I remember one time, when my dull son tried to make pea soup. Would you believe he hadn’t soaked the peas? We almost broke our teeth, all of us. Anyway, when you have soaked the peas, and you’ll want about a cup of them per person, and pay attention because they will expand a bit while they are soaking, so if you aren’t careful they will spill out of whatever you use to hold them, so also use plenty water to soak in, but as I said, about a cup of them, when they are dry, and after they are soaked you cook them in four cups of water per cup of dry peas. Let it simmer for two hours, which means you cover it and keep it barely cooking, and then add some diced onions, sliced celery stalk, and maybe a carrot or two and some ham. Let it all cook for a few minutes more, and it is ready to eat.

Another way to describe this recipe:

Per person: one cup dried split peas, half a chopped onion, half a carrot, a celery stalk, and optionally ham.

Soak peas overnight, simmer them for two hours in four cups of water (per person), add vegetables and ham, and cook for ten more minutes.

This is shorter, but if you don’t know how to soak peas you’ll surely screw up and put them in too little water. But how to soak peas can be looked up, and that is the trick. If you assume a certain basic knowledge in the audience, you can talk in a language that deals with bigger concepts, and express things in a much shorter and clearer way.

Being able to write what we want to do instead of how we do it means we are working at a higher level of abstraction. In practice, this means shorter, clearer, and more pleasant code.”

Haverbeke goes on to show how to encapsulate for-loops in higher order functions (the manner in which he gets there seems so natural that you’ll wonder why anyone ever used a manual for-loop for the purpose of array iteration). There then follows a hefty use case in which we try to map the writings of a hermit to an HTML document. Amazingly even the ‘arbitrary’ example text attributed to the hermit is brilliant, containing much salient philosophizing about language and programming. I particularly enjoyed the following oblique swipe at Java. The last sentence which ostensibly defends Java, doubles as pointed advice to those Java developers who would misuse JavaScript with their narrow-minded approach:

“Tzu-ssu was asked to write a program in the language called Java, which takes a very primitive approach to functions. Every morning, as he sat down in front of his computer, he started complaining. All day he cursed, blaming the language for all that went wrong. Fu-Tzu listened for a while, and then reproached him, saying ‘Every language has its own way. Follow its form, do not try to program as if you were using another language.'”

The chapter rounds out with a nice introduction to functional building-block utilities including function composition and partial application.

Chapter 7, Search, investigates how to write a google-directions style pathfinder module in JavaScript. It’s an excellent case study in refactoring and code re-use (and I learned some neat tricks about pathfinder algorithms). Next comes another gem: Object-Oriented Programming. It begins, as you might expect, with a lucid introduction to the concept. The remainder of the chapter is concerned with building an ingenious terrarium in which insects have minds of their own (perfect OO material – and incidentally the inspiration for my Web Workers versus the Crazy Flies project).

There’s a chapter on Modularity which offers techniques that promote tidy, well-organized program structure, and briefly introduces the concept of third party frameworks. Next comes a well-informed, empathetic guide to Regular Expressions. The book is rounded out by four chapters devoted to Web Programming including a crash course in the basics, an introduction to our infamous DOM model and useful overviews of Browser Events and HttpRequests

Marijn Haverbeke is a software philosopher and all-round genius. He also has a terrific sense of humor and writes both prose and code in a friendly and un-intimidating fashion. In common with the very best teachers he dispenses his wisdom with disarming simplicity. I became a better architect, author, mentor and developer because of this book. It deserves to share shelf space with Flannagan and Crockford.

7 thoughts on “Book Review: Eloquent JavaScript by Marijn Haverbeke

  1. I just discovered the interactive tutorial and was very happy to find such a well-written work on javascript and the art of programming. However, I’m disappointed that the book references some kind of built-in console that I can’t see, either in Chrome or IE. I’m curious to know if anyone has been able to get this feature working, because as it stands now I can’t use the online tutorial at all. It’s been a major disappointment.

    1. Fred (or is it Nigel 🙂 )

      Works beautifully for me in Chrome – there should be a thin strip of blue at the bottom of the screen. Click on it and a decent sized console will appear.

  2. Angus: Thanks! I discovered the problem and wanted to let other readers know in case they run across this issue. There are several versions posted on the website. I had loaded the single-page HTML version to make it easier to save and enjoy off-line. However, it does not contain any of the interactive console features. To see the console and run the scripts, you must click on the version labeled:
    “HTML (interactive) “… I did and it’s working in IE and Chrome too.
    This is a great book. I’m just getting started with all of this and want to learn the right way to do things… (BTW, it is Fred) ha ha.

  3. One small complaint: The lengthy saga of crazy aunt Emily’s cats which serves as both example and exercise gets a little tedious after a while – this is probably the only section that more advanced developers might want to skip.

    I totally agree !!!
    anyway all the rest of the book is very informative and enlightening and not
    boring as that section with the aunt Emily’s cats.
    ohh my god i see cats everywhere 😛
    It is undoubtly a great book for javascript !!!

  4. Hey Angus,

    thank you for sharing your impression about the book, I was looking for someone else’s opinion before starting to read it, and yours surely helped me to decide to go ahead and learn JS from this book.

    Kind regards.

  5. This is an excellent book written by someone who really understands how to convey new concepts with wit. As a relative beginner, I’m not even bothered by the cat exercises 🙂
    I got up to the fourth chapter online before ordering a print copy, just so I could highlight passages and flick through pages at random later on. Thanks for the review.

Leave a Reply

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

You are commenting using your 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