Slashdot is powered by your submissions, so send in your scoop

 



Forgot your password?
typodupeerror
×
Image

Book Review: CoffeeScript: Accelerated JavaScript Development 100

Michael J. Ross writes "For decades, programmers have written computer code in one language, and then programmatically translated that code into another, lower-level form (typically machine code that can be run directly by a microprocessor, or some sort of bytecode that can be interpreted by a virtual machine). For instance, source code written in C or C++ is compiled and assembled into machine code. In web programming, there are emerging languages and other tools for translating code into JavaScript. For instance, Google Web Toolkit allows the programmer to create web apps in Java. The latest addition to this category is CoffeeScript, a language that can be compiled into JavaScript, and is intended to reduce source code size and clutter by incorporating some of the best operators from other Web scripting languages, particularly Ruby. It is also the topic of a new tutorial, CoffeeScript: Accelerated JavaScript Development." Read on to learn what Michael thinks of this book.
CoffeeScript: Accelerated JavaScript Development
author Trevor Burnham
pages 138 pages
publisher Pragmatic Bookshelf
rating 5/10
reviewer Michael J. Ross
ISBN 978-1934356784
summary A fast-paced tutorial of CoffeeScript.
This book is authored by Trevor Burnham, who is credited as one of the early contributors to the project by Jeremy Ashkenas (the creator and project lead of CoffeeScript) in his foreword to the book. Published by Pragmatic Bookshelf on 3 August 2011, under the ISBN 978-1934356784, CoffeeScript: Accelerated JavaScript Development fills only 138 pages, which is certainly a change of pace from the majority of programming tomes now being released. This book's material is grouped into six chapters, plus four appendices — aside from a preface, which introduces CoffeeScript as well as a word game, which is used as the example project throughout the book. Oddly enough, the preface mentions jQuery, but not as one of the well-known attempts to streamline JavaScript code.

The first chapter, "Getting Started," begins by briefly explaining how to install Node and npm (Node Package Manager). These instructions assume that you are following along in a Linux environment or some emulation thereof. They also seem to assume that nothing goes wrong in any of the steps, because no troubleshooting guidance or references are provided. Given the number of moving parts required to get CoffeeScript running, as well as the technical pitfalls that could ensnare a Windows or Mac user, the author should have provided more clear and detailed installation instructions. Also, readers unfamiliar with Linux/Unix may be puzzled by some of the instructions. For instance, page 3 appears to state that the way to check that those two aforesaid packages are on your path, is to simply type in "PATH" (whereas what is needed is "echo $PATH"). From that point forward, the narrative gradually becomes more opaque, with cursory coverage of text editor plug-ins, the "coffee" command line compiler, REPL, "the soak" (an existential chain operator), and the limitations of trying to debug CoffeeScript code. It is quite possible that by the end of this chapter, many readers will decide to not bother trying to learn CoffeeScript, and instead to stick with plain JavaScript, possibly supplemented with jQuery (which is not to say that jQuery code is any easier to read).

In the next three chapters, the author presents the basics of CoffeeScript, including how to: define and use functions and their arguments; test conditionals; throw and catch exceptions; understand variable scoping and context; create arrays using splats; accept input from the console; create objects, arrays, and soaks (in more detail than before); iterate over collections; match patterns; define namespaces using modules; and create prototypes and classes. He makes extensive use of examples, which thankfully are concise (unlike some programming books whose example code span far too many lines, and sometimes even multiple pages — forcing the reader to dig through the code, trying to find the important lines). Also, the brevity of CoffeeScript syntax is undoubtedly a factor. However, his concise style extends to the narrative as well, and will likely cause newbies to have to read the material several times — and even then wonder whether they fully grasp the concepts. It seems that the author understands CoffeeScript extremely well, but is not always able to communicate that knowledge to the reader in a patient and comprehensible manner.

Chapter 5 is a primer on jQuery, and is apparently included in the book so that the example application (the word game) can be made to work in a web browser — since none of the code or narrative (aside from the example app) appears to be related to CoffeeScript. It would have been more efficient to simply point the reader to an online jQuery tutorial, and then present only the CoffeeScript-specific differences — or just briefly explain how to load CoffeeScript files in an HTML file, which could have been done in a sidebar. The last chapter demonstrates how to run CoffeeScript on a web server, utilizing Node.js, and also explores how the lack of threads in JavaScript can impact Node programming. The example project is made multiplayer using Node, Connect, and WebSocket.

The appendices provide answers to the end-of-chapter exercises, alternative methods of running CoffeeScript code, a JavaScript cheat sheet, and a list of a half dozen bibliographic references. This book concludes with a suspiciously-short index, at less than three pages long, which appears to provide only the first or earliest occurrences of the major terms. Consequently, anyone who tries to use this book as a reference work for looking up key terms quickly — or for finding their later occurrences — will likely need to obtain an electronic version of the book, since all e-readers have search functionality. Furthermore, the index is missing some key terms used in the text, such as "function callbacks" and "arbitrary expressions" — heck, it's even missing "expressions," a fundamental concept in any programming language.

Prospective readers who wish to learn more about the book, can visit Pragmatic Bookshelf's page, which offers brief descriptions of the book and its author — as does O'Reilly Media's page. But, as of this writing, only the former makes available an e-book version, pre-publication reader comments, a discussion forum, the example source code used in the book, and a link to a page for reporting errata, which already has more than half a dozen items listed. More are present in the text: "add [a] multiplayer capability" (page xx); a lone ")" missing its matching "(" (in Exercise 6, page 34); "in a lot in functions" (page 107; should read "in a lot of functions"); "a[n] overhead" (page 110); "everyone and their dog is" (page 116).

The author's writing style is sometimes quirky, which in most cases adds a bit of levity, but occasionally leads to the misuse of terms, e.g., array ranges usage described as "fantastical" (page 43). "BDFL" (page xiii) will prove puzzling at first to most readers. On page xvi, the reader is told that JavaScript "contains multitudes." — multitudes of what? And nothing can excuse the groan-inducing "automagically" (page 100).

In terms of the ordering of the topics, one of the most exasperating aspects of this book is the way that many language concepts — such as chained comparisons, and variables being true or false (or "truthy" or "falsy") — are not presented up front, on their own, but mixed in with discussions of other topics, including development of the game application, and even in the answers to the chapter questions (Appendix 1). This makes the book generally unsuitable as a reference, especially when combined with a disappointing index.

One might assume that the modest size of this book is a result of the small size of the language itself. But another factor is surely the pithy presentation style for even some of the most important concepts in the language. Perhaps worst of all — especially from the perspective of someone relatively new to programming — some basic concepts are not addressed, or the example code does not address common use cases. For instance, in CoffeeScript, how does one create a block consisting of multiple lines of code? On page 17, indentation is briefly mentioned, but the sample code shows single-line blocks only. Other important ideas are "saved as an exercise" (which may induce flashbacks to exasperating technical college textbooks). Some readers may conclude that the author didn't want to make the effort of fully describing the language, in a more canonical fashion, which would have resulted in a much longer, but more valuable book.

It is unclear as to how much of the likely mystification and frustration of the average reader will be due to the writing choices made by the author, and how much can be blamed on the sometimes cryptic syntax of CoffeeScript, evident in the discussion of topics such as function binding (Chapter 2) and keywords (e.g., from page 106, "what.x and @x are, of course, equivalent if and only if what is this." Of course!). Readers are told in the introduction that they do not need to be experts in JavaScript to understand the book's material, and can be amateurs (page xviii). But there are several places in the book where intermediate-level knowledge, at a minimum, would be needed. That sort of difficult material may be another point in the CoffeeScript journey where some readers will decide to eschew learning the language.

The production quality of the book is fine, except that the chosen font's ratio of height to width is more than what is usually found in books nowadays; when combined with inadequate spacing among the words within many of the sentences, it makes it difficult for the reader to rapidly scan the material. The e-book version reflects the same minor problem. Yet it makes excellent use of color for syntactically highlighting the code — a feature not seen in the print version.

So if you would like to do some JavaScript programming, but without writing any JavaScript, then one possible place to start your journey is CoffeeScript: Accelerated JavaScript Development. As of this writing, it is the only CoffeeScript book on the market. Yet should the language continue growing in popularity, then more substantial and recommendable books will probably become available.

Michael J. Ross is a freelance web developer and writer.

You can purchase CoffeeScript: Accelerated JavaScript Development from amazon.com. Slashdot welcomes readers' book reviews -- to see your own review here, read the book review guidelines, then visit the submission page.

*

This discussion has been archived. No new comments can be posted.

Book Review: CoffeeScript: Accelerated JavaScript Development

Comments Filter:
  • And then who will write ExpressoScriptDoubleShot?

  • by Anonymous Coward

    It must be such a joy to debug programs written in these higher level languages. Especially on internet explorer, where error messages are practically meaningless.

    • by Anonymous Coward

      It's actually pretty easy; CoffeeScript is almost a line-for-line translation to JS, so it's easy.

      It more than pays off for itself with its terse syntax for routine tasks in JS, like defining functions and re-binding callback functions in the current contexts, something jQuery actually makes less intuitive.

      And the code is a LOT more legible.

      • Hell, yeah.

        I've been writing with Coffeescript, HAML, and Stylus for about a year now, and I'm not looking back. Most IE-specific errors these days are parser errors rather than semantic errors, so JS-Lint takes care of that. And you can't use Coffeescript without knowing Javascript, you just can't; too many libraries are written in JS for you to be unable to read them. And Coffeescript has a node.js mode that rocks.

  • Just what we need.

    • by bl4nk ( 607569 )
      It's frustrating. I work with jQuery/JavaScript daily. I want to contribute to the Chosen project (Chosen [github.com]), but it's written in CoffeScript. I can't be bothered to learn coffee script to contribute. So I'm complaining on Slashdot instead.
      • It's frustrating. I work with jQuery/JavaScript daily.

        Same here. I don't understand why people think that JS is so bad that it's actually better to write in another language and have the JS automatically generated. From C to Assembler the choice is obvious, but JS is already not terribly difficult to use, especially with the libraries available today.

        • Partly because JS is just not nice to look at, and partly because there's just so many ways to do something in JS, it makes it hard to collaborate on a project. Look at constructors for example. CoffeeScripts solution is to take the return value of when an anonymous function calls itself and assign that to a variable. I'm sure there's a good reason why it's done that way but it really drives me crazy to have to look at code like that.

      • by drb226 ( 1938360 )
        CoffeeScript is really not *that* different than JavaScript. Just learn a couple new syntax rules for the same old things. Can you honestly glance over this [github.com] and tell me it would be "difficult" for you to learn CoffeeScript after already knowing JavaScript?
      • by slim ( 1652 )

        If you already know Javascript, I reckon it'll take you less than 3 hours to learn CoffeeScript.

        The brief documentation at http://jashkenas.github.com/coffee-script/ [github.com] , is pretty much all you need. On the same page, you can type CoffeeScript in, and see the generated JS. You'll be there in no time.

    • Just what we need.

      That's what our COBOL forefathers used to say. Seriously, I will never understand why people who make their careers in software decide to make statements like that. Yes, there are always problems with language proliferation, but the alternative is stagnation. We always know more about how to make better software over time, and that inevitably brings changes in tools, languages and paradigms. And you cannot foreseen how much variation is too much (or too little) after the fact.

      If there weren't people pushi

  • I have developed even a better computer language, here is the syntax:

    DO WHAT I WANT

    this is the output:

    # Assignment:
    number = 42
    opposite = true

    # Conditions:
    number = -42 if opposite

    # Functions:
    square = (x) -> x * x

    # Arrays:
    list = [1, 2, 3, 4, 5]

    # Objects:
    math =
    root: Math.sqrt
    square: square
    cube: (x) -> x * square x

    # Splats:
    race = (winner, runners...) ->
    print winner, runners

    # Existence:
    alert "I knew it!" if elvis?

    • That's far inferior to what I have. I give any js task to my nubile red headed Scandinavian assistant whose javascript skills are marginal, who gives a great blow job, and who cares about the money in the bank shit?
      • by Anonymous Coward

        I bet he is lying about his heritage.

      • by jc42 ( 318812 )

        I give any js task to my nubile red headed Scandinavian assistant ...

        That red hair has gotta come from a bottle, because everyone knows that Scandinavians are all blond(e).

        Maybe (s)he's actually Irish or Scottish, and just pretending to be Scandinavian?

        (I have ancestors from all the above areas, so I can get away with mocking the stereotypes of all of them. I couldn't find a way to also mock my French ancestors in this reply, but maybe next time ...)

        • on the serious side, I know some Norwegians that are redheads. no, they do not code nor do they give me head.
          • by jc42 ( 318812 )
            Yeah, and there are blond(e) Scots, too. In both countries, the presence of the stereotype hair color of the other country is generally attributed to invaders in previous centuries. Actually, the people doing DNA analysis have already concluded that there are no statistically significant genetic differences between the populations, or between populations in the north-western half of Europe. The perceived differences are attributable to confirmation bias (and use of cosmetics ;-).
    • Eh, I must be new at this. My input looks the same:

      DO WHAT I WANT

      But the result is this:

      Hello World!

  • Maybe I'll change my mind in the future but I've been dealing with JavaScript for years and I'm not really interested with learning another yet another scripting language, especially one which deliberate collides with JavaScript. Maybe if the syntax was totally different to JS then I'd be interested. I guess now I know how ASM/C programmers feel about C++.
    • by Aladrin ( 926209 ) on Wednesday August 31, 2011 @04:08PM (#37269252)

      I felt the same way until I went to a local coding dojo and they had chosen Coffeescript as the language that week. 2 hours later, I'm a convert. Seriously, it's pretty nice, if for nothing other than dealing with classes in a sane and safe way.

      One of the things they said that convinced me was that the javascript it outputs is much, much better than the equivalent javascript you'd write by hand. And I have to agree... it was very thorough and complete.

      • by Barefoot Monkey ( 1657313 ) on Wednesday August 31, 2011 @05:22PM (#37269720)
        I would like to be a convert too. The functionality of CoffeeScript is wonderful and I like the grammar but the way it handles variable scoping seems like a huge step backwards. It's counter-intuitive, unclear and unpredictable - as though the designers put an enormous amount of effort into removing an aspect of Javascript that worked well and imitating an outdated version of Python instead. If it actually is a good idea and someone could help me see the light and understand the motivation behind it I'd gladly switch over.
        • by slim ( 1652 )

          Can you expand on that point about variable scoping please?

          My perception is that CoffeeScript does the same as Javascript, except that globals are harder to create (good!)

          The JS generated by CoffeeScript pushes variable declarations to the top of the function, so it's clear what the scope is. That's a real gotcha for JS newbies.

          • by Aladrin ( 926209 )

            Maybe he means http://jashkenas.github.com/coffee-script/#lexical_scope [github.com] ?

            Some discussion on why it could be bad: https://github.com/jashkenas/coffee-script/issues/712 [github.com]

            Personally, I tend to use classes extensively, so this is a lot less likely to happen. (Because you need to use "this." or "@" for class variables.)

            • Personally, I tend to use classes extensively, so this is a lot less likely to happen. (Because you need to use "this." or "@" for class variables.)

              I really wonder when in time the meaning of "extensiv(ly)" changed that so many people use it liek you do. In other languages, like german extensiv is used as the opposite of intensiv. In fact the word extensive is rarely used but e.g. in agriculture you would say intensive agriculture, meaning you use a relatively small area and irrigate it and use fertilizer e

              • by slim ( 1652 )

                In the common usage, "extensive" means "having a large extent".

                In agriculture and physics, it can be used as the opposite of "intensive", but it would only be understood among subject expert peers.

  • by Anonymous Coward

    It also makes it 100x harder to track down problems because you're not writing the code in the same language as what it is compiling in to. Trying to guess what line number reported by a browser lines up in your coffee script is going to be a real pain in the ass, especially in larger scripts.

    • by Gorimek ( 61128 )

      Debuggers have been handling this for decades already. You just embed the original line numbers in the generated source.

      Someone is bound to write that debugger plugin, if they haven't already.

    • by slim ( 1652 )

      In practice, it's not that hard.

      When you're debugging, you debug Javascript. Then you figure out what part of the CoffeeScript generated that Javascript. This tends to be straightforward.

      To be sure, it's a negative. But it's vastly outweighed by the legibility of the CoffeeScript, how much faster it is to write, the code quality it engenders.

  • by ptr2004 ( 695756 ) on Wednesday August 31, 2011 @04:45PM (#37269512)
    I thought the problem with javascript was it was weakly typed , dynamic and not typesafe so it was very hard to maintain a really large javascript project. I thought coffeescript would be something more like java so that it was easier to write maintainable code.
    • I thought the problem with javascript was it was weakly typed , dynamic and not typesafe.

      I agree with you... But I have friends who argue that those exact problems are actually its strengths. It boggles the mind.

      • by Anonymous Coward

        in 15 years of coding javascript, I can't say that I've run across any serious problem caused by dynamic typing, even on large codebases (80,000+ loc). JavaScript is extremely predictable once you know how it works. The people who hate dynamically typed languages can't grasp why it isn't the clusterfuck they think it is, so they always put down JavaScript for something they don't know how to deal with.

    • by slim ( 1652 )

      I thought the problem with javascript was it was weakly typed , dynamic and not typesafe so it was very hard to maintain a really large javascript project.

      For the second time this week, I find myself arguing that strong static typing is not something that particularly helps you with large projects. If you write something big, you should be modularising it, and type mismatches aren't easy mistakes to make when communicating between modules.

      No, strong static typing is most useful when you're writing the small, detailed, bit-twiddling parts of your code.

      Fortunately, that kind of work is seldom what you're doing in Javascript.

    • the problem with javascript was it was weakly typed

      JavaScript is not weakly typed, it is dynamic typed, yes but still strong typed.

  • Thanks for the review. The book is aimed mainly at the many developers for whom JavaScript is a secondary language, something they just use to add a little pizzazz to their web pages with jQuery. That's why much of the book is devoted to explaining how scope works, what "this" means, and how prototypal inheritance works—because once you understand the underlying JavaScript, CoffeeScript really is a very simple language. I know you would have preferred a more substantial CoffeeScript book, but there a
  • by Animats ( 122034 ) on Wednesday August 31, 2011 @11:16PM (#37272036) Homepage

    CoffeeScript doesn't actually do much; it's just another syntax for writing Javascript. Javascript is an OK language, Not a great one; it suffers from some of the standard mistakes.

    A classic error is thinking you don't need declarations, and then having to retrofit them. This usually leads to ugly problems, especially if declarations are optional, because the defaults will be backwards. There's a long history of this, starting with FORTRAN and continuing through BASIC and C. Python is almost the only language to successfully work without declarations.

    • Then again, any language is just another syntax for writing Assembler.

      • by voogzy ( 1418593 )

        Don't stop there.
        Assemler too is a kind of syntax sugar for writing machine code. isn't it?
        And machine code is a kind of 'syntax' so you dont have to make special circuits for everything you want it to do, right? :)

        • by maraist ( 68387 ) *
          You make it sound like VHDL is harder to write than assembly.. I assure you it's more expressive than that primitive sequential crap that assembly (and it's higher-level derivatives) forces you to think in. :) And every bit as modular.

Life in the state of nature is solitary, poor, nasty, brutish, and short. - Thomas Hobbes, Leviathan

Working...