Slashdot Mirror


JavaScript: The Good Parts

Anita Kuno writes "JavaScript: The Good Parts is about the good parts of JavaScript and how to use them. This book takes a realistic look at the strengths and weaknesses of JavaScript and tells you how to use it to its best advantage. The code samples deal with the language and its merits — creating web pages is not discussed. How to understand the language, to execute the operations you want, is the focus of the book, not how to make rounded corners. The author, Douglas Crockford says, 'My microwave oven has tons of features, but the only ones I use are cook and the clock. And setting the clock is a struggle. We cope with the complexity of feature-driven design by finding and sticking with the good parts.'" Keep reading for the rest of Anita's review. JavaScript: The Good Parts author Douglas Crockford pages 153 pages includes the index publisher O'Reilly Media Inc. rating 8 reviewer Anita Kuno ISBN 9780596517748 summary The Good Parts of JavaScript. Intended for those familiar with object-oriented programming, who understand inheritance, functions, variables, arrays, and enumeration, it identifies its audience as programmers new to JavaScript as well as those with some familiarity who wish to improve their interaction with the language. People who want to have a good relationship with JavaScript and those who wish to improve the relationship they have will find it most useful. There are lots of books and tutorials that deal with JavaScript but this approaches the language from the point of view of a survivalist.

I expect this little field guide to retain its usefulness for many years. As Brendan Eich, the creator of JavaScript, states on his blog, "What was needed was a convincing proof of concept, AKA a demo. That, I delivered, and in too-short order it was a fait accompli." JavaScript was a mock up that got a stamp of approval. His first draft became the language. I find that rather shocking. But Brendan alludes in his blog to the idea that there were many other considerations in play at the time, so the story-boarded code got the go-ahead. Crockford's book fills a niche for users explaining how to code with JavaScript and be a better programmer because of the experience.

Douglas Crockford writes in a relaxed, conversational style establishing a connection with the reader that continues through the book's contents (all 100 pages) and the five appendixes ( 50 pages total for the appendixes). I read the book in an evening-away-from-the-screen kind of mood and only followed one piece of code as outlined in the book. The book is approachable with a cursory acknowledgment of the code and it is also informative with a detailed examination of said code.

Special mention goes to Chapter 7: Regular Expressions. There are some topics which are so complex that other authors either skip over them, or use so much jargon as to render the effort useless. Douglas Crockford gives a guided tour of a regular expression designed to parse a url and it is intelligible and informative. He identifies the shortcut he uses in his regular expression code and acknowledges the risks he accepts by using it. I found his twelve and a half pages on regular expressions gave me a reasonable introduction to the subject.

He uses quotes from Shakespeare as an icebreaker for each chapter and appendix. The book contains code snippets and some recipes for adding your own functions and methods which Douglas feels should have been in the language and aren't. This I find to be a very interesting feature of the book. Like the staples for a good kitchen: ganache, bechamel, mirepoix; Crockford identifies the staples of a scripting language and gives the reader the recipes for the features that JavaScript doesn't have; .integer, .trim, and .curry (which allows the creation of a new function by combining a function and an argument).

One of the things that is missing from this book is the DOM (the Document Object Model). I couldn't be happier about that. Every other reference I have approached mashes JavaScript to the DOM so fast that as a newcomer to the language I thought that aspects of the DOM were properties of JavaScript. Douglas Crockford has an episode on Yahoo! Video talking about that very topic and it was a breath of fresh air for deciphering JavaScript. By the way, the amount of characters, in the above sentences about the DOM, is about the quantity of characters dedicated to the topic in JavaScript: The Good Parts. For me, this is a plus.

The author states that the necessary equipment for writing JavaScript programs is a browser and a text editor. Since both are readily available in a variety of flavors and styles, I am fairly confident that every programmer wanting to learn about the good parts of JavaScript can do so.

My previous attempts to learn JavaScript had not gone well and I didn't have an understanding about why the topic was proving so confusing for me. Knowing the history of the language and the environment at its birth, I now have a better appreciation for the abilities of this language as well as a higher level of acceptance for its quirks. I understand now why I should use "var" when assigning a variable, and also why it is a good idea to conclude the line containing "return" that is followed by a block, with the left curly brace that begins the block. I didn't have the patience to accept these idiosyncrasies before and now that I know the history of JavaScript, I can see why it is a good idea to use Crockford's suggestions as a consistent coding style.

Charles Jolley suggested that I read JavaScript: The Good Parts as a basis for learning JavaScript. His tag line was: "I read it in three hours." Now, that may be an inappropriate reason for reading a book, but after spending hours and hours with various media trying to understand JavaScript, three hours seemed like a reasonable investment of time. (It took me a little longer reading at home with the occasional interruption but I still did my first pass in an evening.) The author wrote the book as an enumerable (the recipient of an action one or more times) with each reading revealing layers of understanding.

In the appendixes, there is an appendix entitled "Awful Parts" and one entitled "Bad Parts". Global variables head the list in "Awful Parts". There are discussions throughout the book about why to avoid JavaScript's default to global variables and how to do this in your coding style. The explanation, of why global variables should be avoided in JavaScript, is detailed in the "Awful Parts" appendix. Also making an appearance in "Awful Parts": scope, semicolon insertion, and reserved words. The "Bad Parts" appendix includes: == (double equal sign) which can be evaluated unpredictably depending on the circumstances, "with" which can also have unpredictable results, and "eval" which passes a string to the JavaScript compiler and executes the result. "eval" slows the result when compilation isn't required and can also compromise the security of your application. But what about its use in JSON you ask? Crockford suggests using the JSON.parse method instead of "eval". The file which creates the JSON object with the parse method can be found here. If this is of interest to you, I suggest you check the link and access the book to hear it from Crockford directly.

I find Douglas Crockford's perspective on JavaScript in JavaScript: The Good Parts to be useful in my own relationship with JavaScript. His style is accessible and intelligent.

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

17 of 162 comments (clear)

  1. One browser? by Benbrizzi · · Score: 4, Informative

    The author states that the necessary equipment for writing JavaScript programs is a browser and a text editor.

    You need waaay more thane ONE browser to write JavaScript. There are still so many cross-browser incompatibilities with javascript today you pretty much have to write one script for firefox and one for IE each time you code.

    1. Re:One browser? by xactoguy · · Score: 5, Informative

      Most of those cross-browser incompatibilities are actually with the DOM model, not the underlying JavaScript implementation. While IE 5.0's implementation* had some notable bugs (String.slice() and String.substr() along with a fair bit of the assert() functionality), things are pretty compatible these days until you start using the DOM. * Opera 6 and below as well as Netscape 4 and below had some interesting quirks too, but those browsers are beyond the memory of most modern web-designers.

      --


      And so we go, on with our lives
      We know the truth, but prefer lies
      Lies are simple, simple is bliss
    2. Re:One browser? by Bogtha · · Score: 4, Informative

      You need waaay more thane ONE browser to write JavaScript.

      Not all JavaScript is intended to be executed in browsers. Server-side JavaScript was introduced a year after client-side JavaScript, and desktop scripting in JScript has been available in Windows for a decade as part of Windows Scripting Host.

      You don't need more than one browser to write a JavaScript program, you need more than one browser to develop a website. These are two very distinct things.

      There are still so many cross-browser incompatibilities with javascript today you pretty much have to write one script for firefox and one for IE each time you code.

      Actually, there are very few incompatibilities between JavaScript implementations. It's the DOM that is the cause of most incompatibilities, and all the major libraries like jQuery, Prototype, etc, abstract those difficulties away. Modern JavaScript development is not a case of writing two different scripts. In fact, even without the help of libraries, that style of development was mostly obsoleted when Netscape 4 died.

      --
      Bogtha Bogtha Bogtha
    3. Re:One browser? by uhlume · · Score: 3, Informative

      Of course, the vast majority of those incompatibilities are due to inconsistencies in implementation of the DOM — which the book under review explicitly chooses not to address. Take the DOM out of the picture, and the core JavaScript language is fairly consistent across all modern browser implementations. In the context of the language as covered in this book, a single browser is probably a pretty safe requirement.

      --
      SIERRA TANGO FOXTROT UNIFORM
    4. Re:One browser? by Bogtha · · Score: 2, Informative

      The original quote makes no mention of serverside scripting, it makes mention of a browser. Therefore any reference to javascript is assumed to be executed within a browser.

      How do you propose that web developers test server-side scripting? Telnet to port 80 and type the requests by hand?

      Yes, you want a web browser when you are writing server-side JavaScript. No, that doesn't mean that it is executing within a browser.

      Response, you dont have to use more than 1 browser if you use an OO library

      I never said that at all. I disagreed with the assessment that cross-browser JavaScript incompatibilities require developers to write two different scripts, and I said that part of the reason for that was the availability of libraries that mitigate the problems with the DOM.

      if you're going to be literal about only needing 1 browser to write javascript (which you arent even doing anymore if you only use an api)

      Using an API means that you are no longer using the same language? Now you're just being silly. You aren't arguing because you think you are right, you are just arguing for the sake of it. JavaScript is JavaScript regardless of whether you access the DOM directly or make use of a library. Besides, the DOM is an API, so by your logic, it's pretty much impossible to write JavaScript to execute in a browser at all.

      Javascript requires knowledge of a browser's DOM implementation to display anything.

      WScript.Echo("No it doesn't.");

      <%@LANGUAGE="JavaScript"%>
      <%
      Response.Write("It really doesn't.")
      %>

      --
      Bogtha Bogtha Bogtha
  2. Scoping is Awful? by PipianJ · · Score: 3, Informative

    I must admit that JavaScript's method of scoping isn't the best (mostly because it has variables that can be reassigned, and scoping binds to the variables, not the values) but I can say that scoping is a time-saver if you do it right and (for example) have a bunch of anchors that all need slightly different arguments in their onclick event handlers.

    I've more than once used something like:

    function onclickGenerator(i) { return function() { doSomething(i); }; }

    var elements = document.getElementsByTagName('a');
    for (var i = 0; i < elements.length; i++) { elements[i].onclick = onclickGenerator(i); }

    It would be nice if it treated scope by binding values, not variables though... (If you tried doing the above by replacing onclickGenerator(i) with function() { doSomething(i); }, every element would end up calling doSomething(elements.length);, instead of doSomething(value_of_i_at_onclick_set_time);

    1. Re:Scoping is Awful? by larry+bagina · · Score: 3, Informative
      Ick. Requires an eval. What if you need to pass a string or an object?

      Extend function.prototype a bit:

      bleh.onclick = doSomething.bind(null, {one: 1, two: 2});
      bleh.onclick = doSomething.curry("...");

      (also, you should use level 2 events, but that's another issue).

      --
      Do you even lift?

      These aren't the 'roids you're looking for.

  3. The author's website by DCstewieG · · Score: 5, Informative

    Crockford's website has a bunch of great articles about JavaScript. I've learned quite a bit from there.

    http://www.crockford.com/javascript/

  4. browser fucking by MightyYar · · Score: 3, Informative

    Are you really required to support older versions of Safari? I only have 3.1.2 and that page that you linked to works as described - so it appears to have been fixed.

    --
    W..w..W - Willy Waterloo washes Warren Wiggins who is washing Waldo Woo.
  5. javascript/lisp connection by Phantom+of+the+Opera · · Score: 3, Informative

    Javascript itself is a relative of scheme, which is a descendant of lisp.

    It offers macros, closures and of course recursion.
    The big difference is that javascript is not list based.

  6. Crockford's instructional vids by spads · · Score: 3, Informative

    Though they were the logical starting point, I am grateful to be mainly past my reliance on books. However, based on how good his videos (e.g. http://javascript.crockford.com/, http://yuiblog.com/blog/2007/01/24/video-crockford-tjpl/) are, I would consider checking this one out.

    --
    Bukowski said it. I believe it. That settles it.
  7. No .trim??? by TheUnknownCoder · · Score: 2, Informative
    String.prototype.trim = function(){return(this.replace(/((^\s*)|(\s*$))/g, ""))};

    There you go.

    --
    Uncopyrightable: The longest word you can write without repeating a letter.
  8. Re:the only problem with javascript by appleprophet · · Score: 2, Informative

    Safari (actually, I believe you mean WebKit) is the biggest offender? +4 insightful? Are you fucking kidding me?

    I'd like to see an example of what you mean by offensive, because WebKit is the most standards compliant browser in existence. Internet Explorer is less offensive than Safari? Give me a fucking break.

    Every commit in WebKit causes the JavaScriptCore code base to run thousands of regression tests, including FireFox's. These test virtually every aspect of JavaScript, including specifications that IE does not even support yet! If there is a single regression, the commit is rejected.

    I know you are talking out of your ass, but shit like this really pisses me off for some reason. The hundreds of developers for WebKit deserve better.

  9. its simple by circletimessquare · · Score: 2, Informative

    document.onclick=function(){
    blah blah
    }

    then cancel event bubbling and default action, according to normal ie and firefox methods

    the anchor tag is not modified in any way. the href goes nowhere

    and i've tried to cancel the default action in safari in myriad ways, but it always tries to follow the bogus href ;-(

    --
    intellectual property law is philosophically incoherent. it is your moral duty to ignore it or sabotage it
  10. Great book - try out the online 'debugger' by __aanjtz122 · · Score: 3, Informative

    I really like this book. The author does not treat you like an idiot or make 'oh so funny' jokes to make you feel comfortable with the text. The writing style is friendly and fluid, while the content is always to point. I wish more programming books were as dross-free as this one.

    Many readers are likely to read through sections twice or a few times. Crockford warns, 'This book is small, but it is dense', and it is certainly is cramed with useful information. The author states no intention of writing a JavaScript reference but has certainly written a book that I will pick up frequently on JavaScript projects

    I am surprised the reviewer didn't mention JSlint a free, online JavaScript 'verifier', written by the author, that can be used to 'debug' and write better code. It may even be worth a try before you buy the book.

  11. Re:the only problem with javascript by Pollardito · · Score: 3, Informative

    IE is undoubtedly worse than Safari and its cryptic error messages when something doesn't work are a big reason not to code anything in IE first, but Safari has had it's issues. It used to be that you could not change the value of a radio button control with JavaScript in Safari. I remember implementing a page that had an extra hidden variable for every radio button that I wanted to have an editable value just because of this particular problem. There are some quirks when reading back values that you've written into an innerHTML (all HTML tags come back capitalized and any HTML comments that were in the string you wrote into the value come back stripped out), but I doubt that is something that many people have run into.

  12. Re:that example is old then by Fweeky · · Score: 3, Informative

    Do you have a test case showing what you're doing then? Because document.addEventListener("click", function(event) { event.preventDefault(); }, false); and document.onclick = function(event) { event.preventDefault(); } both work fine in 3.1.2 here.