Forgot your password?
typodupeerror
Book Reviews Books Media

The Book of JavaScript 83

Posted by samzenpus
from the read-all-about-it dept.
Michael J. Ross writes "Developers of Web sites, whether professional programmers or Web hobbyists, are oftentimes impressed by the more advanced functionality that can be achieved on a Web page using JavaScript. Yet these personal discoveries of JavaScript's power do not always motivate the developers to implement similar functionality on their own sites — partly because most of those custom-built JavaScript functions are cryptic, and make no attempt to show how the developer would customize the code for their own use. The majority of JavaScript books are of limited help in this regard, because they focus on the language details, illustrated only with code snippets. Many readers would benefit more from instruction via working examples, which is the approach used by The Book of JavaScript." Read the rest of Michael's review.
The Book of JavaScript
author David Thau
pages 528
publisher No Starch Press
rating 8
reviewer Michael J. Ross
ISBN 1886411360
summary A guide for beginners to learn JavaScript via examples


The book was written by David Thau, a.k.a. "thau!," a veteran of the Internet and computer programming — especially JavaScript, which he has taught to countless other programmers, through this book, as well as numerous courses, conference presentations, and the tutorials he has written for Webmonkey.

Published by No Starch Press, the second edition of The Book of JavaScript appeared in December 2006. The publisher maintains a Web page for the book, where visitors can find an online copy of the book's table of contents, excerpts from reader reviews, links for purchasing the paper and electronic versions of the book, a sample chapter ("Chapter 2: Using Variables and Built-In Functions to Update Your Web Pages Automatically") as a PDF file, the errata discovered by the author and readers (several reported so far), and a link to the author's companion site.

Unlike some books' companion sites, this one is worth a visit, and not just to see a working example of the tip box described in chapter 8, which is used to show how to create an array. Thau's site has links for viewing, running, and downloading all of the sample code in the book's figures. In addition, the visitor can obtain copies of the book's JavaScript libraries, for doing cookies, form validation, and plug-in detection. There are links for viewing and downloading the three sample Web sites. However, in his AntWeb site, at least as of this writing, none of the images are showing up on his homepage. Another problem, of much less importance, is the strange behavior of the "Websites" and "Freeware" options on his "Chapters" drop-down list box. Choosing either one takes the visitor to his "Websites" page, but always displays "Freeware" in the drop-down. It is hard to imagine that this behavior is intentional.

The book's material spans 528 pages, most of which is found in 18 chapters, covering a variety of topics: an overview of JavaScript's capabilities, alternatives, and limitations, among other less technical issues; variables and built-in functions; browser detection and simple control flow; rollovers, events, images, and the "document" object; window manipulation and properties; creating your own JavaScript functions; Web forms; arrays and iteration; timing events; frames and image maps; handling form input and strings; cookies; dynamic HTML, CSS, and DOM; AJAX basics; XML; server-side AJAX; a sample application (an online to-do list); and debugging JavaScript and AJAX. The book also offers four appendices: answers to chapter assignments; online resources (tutorials, sample code, AJAX sites, and AJAX frameworks); a complete reference to JavaScript's objects and functions; the code for the book's two longest applications, namely, the Italian translator and the to-do list.

This second edition serves as a follow-up to the well-regarded first edition that came out seven years earlier. Both the book and the language itself have clearly withstood the test of time. There are several reasons for the popularity of that first edition: It taught the language and its capabilities largely through the use of complete JavaScript functions, each of which served as an illustrative example of not just the elements and rules of the language, but also straightforward ways of accomplishing common tasks in JavaScript. After all, looking at sample code is how most programmers prefer to learn or verify how a language works.

The book assumed no prior knowledge of JavaScript or any other computer language, on the part of the reader. This characteristic not only set it apart from the large number of other JavaScript titles published at that time, but it made the book more attractive to people new to programming in general and Web programming in particular. Such readers might also favor this book over others because of the author's approachable writing style, in which he fully explains topics in a leisurely manner, without the terseness seen in most programming language books. This is not to say that brevity in technical works is ever a mistake per se; the busy professional programmer wants to find answers as quickly as possible. But such brevity can quickly prove frustrating to non-techies, who lack the background for understanding terse explanations and for knowing where they can turn for clarification.

All of these laudable attributes of the first edition have been carried over into this latest edition. The primary change found in this second edition, is the coverage of AJAX (asynchronous JavaScript combined with XML). Even though the additional material substantially increases the length of the book, by 124 pages, the end result is still far from unwieldy — mostly due to several factors: The book's table of contents, along with the index, are detailed enough to make it relatively easy to find a particular topic in the book, assuming that it is included. The subsection listings in the table of contents, like good source code, make liberal use of whitespace for readability. In the text itself, coloring the headings and note numbers blue make them stand out.

Aside from the aforesaid problems with the book's companion site, there are a few other areas for improvement: It was noted earlier that the last appendix contains the sample code from chapters 15 and 17. The author states that these code listings were located in an appendix, rather than the chapters themselves, because they are too long. Actually, they comprise only a dozen pages, which would have been better located in the chapters where the reader expects to see them, and where they would be close at hand for referencing. The first listing is only two pages long, and definitely should be located in chapter 15. Even for the second listing, if the author is concerned about readers getting frustrated flipping through the 10 pages to find the continuation of the chapter's discussion, a simple note at the beginning of that code, as to what page the discussion is resumed, would be sufficient.

Some fundamental language elements of JavaScript are introduced fairly late in the book. For instance, it is noted above that an explanation as to how to create an array — an essential concept in just about any procedural language — is not found until the eighth chapter, on page 134. This is more than one third of the way into the book's 18 chapters. On the other hand, given that the author has chosen to present these language concepts, for the most part, only when needed and when describing the sample code, this later introduction of some key concepts might not prove much of a problem to most readers. However, this is a case in which the completeness and accuracy of the book's index, are even more critical than usual. In this regard, the book does not fail the reader, as the index appears to provide enough coverage.

The formatting of the code throughout the text is not entirely consistent, as evidenced by some open braces appearing on their own lines, thus wasting space, and in other cases on the same line as the preceding parenthesized expression, though separated by a pointlessly large number of spaces. Code level blocks are indented two or four spaces, seemingly at random. Continuation lines are indented exactly the same; they would be more clear if they had double the number of spaces as code level blocks. Of more importance to the reader attempting to figure out what code is serving what purpose, there are far too many large chunks of code lacking any comments, which are needed, since much of the code is not self-describing. In most of the functions, the only comment lines are those for hiding the JavaScript from outdated browsers — a practice that should have been phased out in this latest edition.

Any experienced programmer who needs a complete JavaScript reference book, or a book that covers all the language's elements in fine detail, would be best served by choosing a different book from this one. On the other hand, once they had secured such a book, they would likely find David Thau's contribution an enjoyable source of ideas on what can be done using JavaScript capabilities. For anyone who wishes to learn JavaScript in a practical and relaxed way, by reading clearly explained sample projects and their code, should be well pleased with The Book of JavaScript.

Michael J. Ross is a Web programmer, freelance writer, and the editor of PristinePlanet.com's free newsletter. He can be reached at www.ross.ws, hosted by SiteGround.


You can purchase The Book of JavaScript 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.

The Book of JavaScript

Comments Filter:
  • Javascript: It's Not Just for Annoying Spammy Popup Ads Anymore!
    • by FooAtWFU (699187) on Wednesday March 07, 2007 @03:48PM (#18266988) Homepage
      Poor JavaScript is the world's most misunderstood programming language [crockford.com]. But it's really kind of neat. The browser environment isn't too hot, but aside from that and a few stupid quirks (string concatenation / addition issues, especially) it's a neat little programming language where functions are actually first-class objects; you can do some pretty nifty inheritance things with this, building objects' behavior by aggregation...

      Of course, you'll need a decent library like MooTools or Prototype or such if you want to keep your programming sane, and especially if you want to do good stuff in a web browser (they abstract away an enormous swath of the IE vs Mozilla-type vs Opera/etc compatibility issues).

      • by gfxguy (98788)
        That was always my problem for any kind of heavy use of Javascript. I use it for a few convenience things, but I balk when I have to have the same code multiple times for various browsers, or have my code littered with if's to determine if it's IE to either not do something or do something extra.
        • Re: (Score:3, Informative)

          by hobo sapiens (893427)
          Yeah, that's the way it used to be. Prototype is what I use, because along with a very useful AJAX library it has several useful tools that totally abstract browser differences. For example, it has the $() function. Plug the id of an element in there like such: $('chewbacca'). Assign that to a var, and you have an object var that references the fully qualified element regardless of which browser you are in.

          That's pretty simple actually. I used to have my own library that did that and more. But Proto
      • a few stupid quirks (string concatenation / addition issues, especially)

        Yeah, my favorite one right now is how datevar.getYear() returns 107 in Firefox and 07 in IE. Just use datevar.getFullYear(), I know. But still...if you didn't know that imagine how frustrating it could be to have some date code return different stuff in different browsers?

        Just like you said, aside from stuff like that, javascript is very powerful. Everyone has a somewhat new browser, so everyone can use it.

        • by lazybeam (162300)
          What was the function that returns 2007 in 2007 but returned 99 in 1999? I always think of that misfeature when I hear the Gorillaz song 19-2000. :) (That was a common Y2K bug, people concatting "19" to a two-digit-year function)
      • The fact that functions are objects is cool but I have many complaints about JavaScript. The implementation of object orientation as a hash table with a dot notation is a far cry from object orientation.

        I have never used a java script environment outside of a web browser so I pretty much associate the two as the same. The fact that the this keyword has very different semantics depending on how the member function was called is a major stumbling block for me. Yes, prototype binding saves the day but it r

        • by FooAtWFU (699187)

          The fact that functions are objects is cool but I have many complaints about JavaScript. The implementation of object orientation as a hash table with a dot notation is a far cry from object orientation.

          What difference does that make to you as a programmer, practically? Any dynamically interpreted language already uses a hash of some sort for runtime resolution of values in symbol table. Is this somehow less valid because it isn't precomputed? I guess you lose some of your type-safety-ness and are allowed

          • So what object-orienting features exactly are you looking for that JavaScript doesn't provide?

            Proper overriding of members such that the base class implementation is still available (e.g. super.mymethod()).

            The one thing I could see you complaining about is data hiding and private variables - okay, those are a little trickier and involve setting an object's functions that use these private variables in the constructor at runtime.

            Any well defined task can be programmed in any general purpose programing language. So whether or not something is possible is not a good measure of a programming language. By that criteria, all general purpose programming languages are identical. Rather, how easy it is to do something is a better measure of a programming language. Yes, it is possible to fake all kinds of object oriented f

      • by CTho9305 (264265)
        I like JS. Taken together with canvas, you can do some pretty interesting things: some toys [ctho.ath.cx] (including a 3d graphics engine) and some games [ctho.ath.cx] (see if you can beat the Robots high score). I think this game [ctho.ath.cx] is probably the most interesting (unfortunately I never got around to implementing the transportation logic, but it's still an amusing demonstration of what's possible).

        I got into this originally because I spend a lot of time working on SeaMonkey (and sometimes Firefox / Thunderbird), which has huge amount
      • The browser environment isn't too hot, but aside from that and a few stupid quirks (string concatenation / addition issues, especially) it's a neat little programming language where functions are actually first-class objects; you can do some pretty nifty inheritance things with this, building objects' behavior by aggregation...
        Oh, just like you can with Lisp, Scheme, Smalltalk, Standard ML, and Perl?
    • Re: (Score:1, Funny)

      by balbord (447248)
      <script language=javascript>
      while(1==1){
      alert('pwned');
      }
      </script>

      Mwhahahahah
      Phear my mad skillz!

      Hunrf?!?!
      • Browser: "This script appears to be running slowly. Would you like to kill it?"

        Me: "Yes<click>, please"

        Browser: "Would you like me to smack balbord while I'm at it?"

        Me: "Yes<click>, please"

        (Okay, so that last part doesn't really happen. But there's always hope in the next version of Firefox!)
  • by revlayle (964221)
    AJAX is not "asynchronous JavaScript combined with XML" - 'cause, then, that would be AJCWX, and that is totally unpronounceable. ;)
  • Developers of Web sites are oftentimes impressed by the more advanced functionality that can be achieved on a Web page using JavaScript. Yet these personal discoveries of JavaScript's power do not always motivate the developers to implement similar functionality on their own sites

    If I may make a supposition, this occurs most often because programmers think they know how to program in Javascript, but don't have the first clue. That's why we see lots of code like:

    <body onKeyDown="doSomeStuff()">
    Or:

    domelement.innerHTML = "<p>"+equation+"</p>";
    Anyone want to guess what happens when "equation" is equal to "x

    function doSomeStuff(event) {...}
     
    document.addEventListener("keydown", doSomeStuff, false);
    ^^-Much more portable as it can be constrained to a single JS file without overriding the ability of other code to receive events.

    var paragraph = document.createElement("p"); //this should really be a DIV
     
    paragraph.appendChild(document.createTextEl ement(equation));
    domelement.appendChild(paragrap h);
    ^^-Seems more complex, but does not suffer from special character issues -AND- can be far less code when used in well-written algorithms.

    Then there are people who do this:

    for(i=0; i<10; i++) doSomething(i);
    I hope you don't have a loop in doSomething, because you may accidently modify the global variable "i". The correct solution is to make it a local variable like this:

    for(var i=0; i<10; i++) doSomething(i);
    Lastly, people complain that Javascript isn't Object Oriented. To which I can only act annoyed. What is this?

    function LightBulb(on)
    {
        this.on = on;
     
        this.isOn = function() { return this.on; }
        this.setOn = function(on) { this.on = on; }
    }
     
    var mybulb1 = new LightBulb(true);
    var mybulb2 = new LightBulb(false);
     
    alert(mybulb1.isOn()+" - "+mybulb2.isOn());
    If that still doesn't convince you to take another look at Javascript, well maybe this will:

    http://www.youtube.com/profile?user=thewiirocks [youtube.com]

    It's a set of videos showing Javascript games in development for the Nintendo Wii. Nothing special here, just Javascript + Canvas. The Tetris game even has a demo here:

    http://java.dnsalias.com/tetris/ [dnsalias.com]

    Make sure you have a browser that doesn't suck.

    I hope you all consider taking another look at Javascript. Maybe this book is for you, maybe it isn't. But there is a LOT of potential to release.
    • Ha! I got bit by my own bug! This:

      domelement.innerHTML = "<p>"+equation+"</p>";

      Anyone want to guess what happens when "equation" is equal to "x

      is supposed to say this:

      domelement.innerHTML = "<p>"+equation+"</p>";

      Anyone want to guess what happens when "equation" is equal to "x < y"? (Hint: Nothing good.)

      Just more proof of why coding for the DOM is a good idea. Microsoft's extension crud may seem convenient at the moment, but it's just hurting you in the long run.

      • If you wrote "equation = x y", then of course nothing good will happen, equation is effective a bool and will get toString()'d during concatenation.

        However, most of your examples don't have squat to do with the core language, and everything to do with the DOM. Or what *you* think is a useful way to express an idea.

        Just because it's possible to manipulate the DOM to insert an event listener doesn't mean that it's practical. Especially in the case when your attaching say events to HTML elements that run java
    • I have no reason to be annoyed with "Javascript is not object-oriented", because it really is such an obscure bit of information. You're actually the first place I've ever seen to even mention it. Sure, I've noticed it used in some places, to which I thought "Javascript is object oriented? I didn't know that.", but nobody seems keen to tell anyone else ;)
      • "Javascript is object oriented? I didn't know that.", but nobody seems keen to tell anyone else

        The frightening part is that it's not that obscure. The Client-Side Guide [sun.com] that Netscape used to publish (up until the ECMA standard was established), has several detailed sections on written OOP code in Javascript. Including multiple methods for handling inheritence! The problem is that no one read Netscape's documentation. Everyone "learned" Javascript by modifying some poorly-written script they found on the In

        • by FireIron (838223)
          Gosh darnit AKAImBatman, stop spreading the secret of OO-JS everywhere!!! How are we supposed to look like genius web programming wizards if everyone knows how our tricks work?

          ;-) j/k ;-)
        • by Gospodin (547743)

          Heh, yep. I've been interviewing potential web application developers for months, and one of the things I try to probe is how much they really know about Javascript. So far I've met exactly zero who knew more than <a href="javascript:void(0)" onclick="alert('kewl')">.

    • by iluvcapra (782887)

      Lastly, people complain that Javascript isn't Object Oriented. To which I can only act annoyed. What is this?

      That's a first-class function or closure, not a class. You still can't do class or private and protected methods using this hack, nor can you do any meaningful inheritance or mixins.

      You're right, Javascript is a good language with an unfortunate reputation, but it ain't object oriented. Its functional, and thus frameworks are built with first-class function and closures.

      • You're right, Javascript is a good language with an unfortunate reputation, but it ain't object oriented.

        You don't need a class/method design to be object oriented. Only the OO purists are dead-set on that. OOP is a style of programming, with some languages providing first-class support while other's do not. Nearly every language can be coded in an OO-manner to some degree. Javascript, thankfully, got fairly decent support from the get-go despite its intended use as procedural scripting. That makes a big di

        • by iluvcapra (782887)

          Thanks for the link, that's interesting.

        • by suv4x4 (956391)
          This link is a good way to win in a discussion with ill-informed opponents.

          Scope hacks are not a way to achieve member visibility, it's just that: a hack.

          It adds overhead to the constructor, wastes memory by keeping the construction activation object alive long after the constructor function has returned, doesn't let the public methods access the "private" ones (ooops...), doesn't resolve the issue of protected members.

          Well, for protected members maybe it doesn't matter since extending "classes" in JS is he
      • by Maian (887886)
        Private members

        Do you consider Python to be object-oriented? The "private" members of classes on Python are defined such that the names are prefixed with 2 underscores, i.e. __foo is private while bar isn't. The private var names are mangled so that they aren't easily accessible outside the class, but they are still technically public.

        You can use this same idiom with JavaScript - just prefix the members you intend to be private with 2 underscores (or something equivalent). There's no name mangling in J

    • If I may make a supposition, this occurs most often because programmers think they know how to program in Javascript, but don't have the first clue. That's why we see lots of code like:

      Well, sure, I'm with you on this one, but you have to admit that this is how most of those programmers are "teached" from javascript documentation sources (not even mentionning those "100 great javascripts" web sites). The diversity and absurdity of documentation surrounding JS and web development reached a dangerous level. I
      • by MemeRot (80975)
        If you're looking at performance a lot, declaring your loop variable outside of the loop helps. Which makes sense, why declare it every time you loop, but doesn't match any of the normal code you see out there.
    • by suv4x4 (956391)
      Congratulations, you're a zealot. Who exactly invited you to paste your default JavaScript rant here, simlpy because the article is about a JavaScript book? Did you just wanna "let it out" since noone around you has idea what JavaScript means?

      Both the DOM API and innerHTML have their place, and event handlers attached in the tag as attributes, and even eval() (yes OMGWTFBBQ!! I suck!!) can be useful for plenty of purposes, next to the "better" approaches you advertise.

      You're simply repeating well known clic
      • Who exactly invited you to paste your default JavaScript rant here, simlpy because the article is about a JavaScript book?

        1. It's not a default "cut and paste" rant. It's one I made just for this article. ;-)

        2. That "Reply" button looked awefully inviting...

        If truly you're wondering why I suddenly broke into a rant, it's because I've seen these articles too many times. Everyone assumes they already know Javascript, ergo, this book is not targeted at them. Well, someone needed to burst their bubble. Just loo

        • by suv4x4 (956391)
          Funny, I was just mentioning that to another poster elsewhere in this thread. Perhaps my post was what gave you this idea? ;-)

          Indeed! So I just pasted it from your response, in case you forgot what you were talking about exactly 47 seconds ago!

          BTW, Flash implements most of ECMAScript 4.0 in ActionScript 2.0. Which is Flash version 7.

          If you can say "most" when Flash 7 implemented loosely the class syntax at compiler time, on top of their extended prototypes engine, added types only as a compiler time check a
    • by suv4x4 (956391)
      What is this?

      function LightBulb(on)
      {
      this.on = on;

      this.isOn = function() { return this.on; }
      this.setOn = function(on) { this.on = on; }
      }

      var mybulb1 = new LightBulb(true);
      var mybulb2 = new LightBulb
      • If I'd shown them the Prototype method, I would have royally confused them. The inline method uses more memory, but it's much closer, syntactically, to what most people think of as an "object".

        Ah well, at least someone's keeping me honest. :)
    • > If I may make a supposition, this occurs most often because programmers think
      > they know how to program in Javascript, but don't have the first clue. That's

      Amen. The situation out there is actually so bad, it boggles the mind how so many web developers continue to earn a paycheck. Want evidence? Turn on JS debugging/error messages in your browser (esp. IE) and spend a week or two battling the deluge of error dialogs before you turn it off again in disgust. If people can't be bothered to write ro
  • I no how to program in php and C (enough to do what I want). I just cant wrap my head around java.
  • by davidwr (791652) on Wednesday March 07, 2007 @04:28PM (#18267450) Homepage Journal
    I haven't RTFBook but any good web-development book must show how to code for graceful degradation. I hope this book does this.

    Many web browsers do not support all features of JavaScript, and many that do allow users to disable certain features.

    Handling these situations gracefully is essential to any good web site. Features such as JavaScript should be used to enhance a web site, not provide basic functionality.
    • To solve this problem I've found libraries such as prototype and scriptaculous most helpful. As long as they're used properly and mostly for visual enhancements they are cross-browser and degrade nicely. If a client asks for a rich text box, I usually choose implementations which gracefully fall back to plain text boxes.

      But these days it's very hard to convince non-techies that web sites should often not require javascript for basic functionality. They see gmail or whatever and assume everyone on the net
    • by GeckoX (259575)
      There is but ONE rule you need to know to deal with ALL browser specific issues.

      If in doubt, TEST the functionality before calling said functionality.

      Do NOT insert code switches based on browser sniffing. Never ever ever.

      It really is just that simple.

  • is this [prototypejs.org]. Seriously.
    • I wouldn't go down the prototype/scriptaculous route. Those libraries are powerful, but so is jQuery [jquery.com], and it's much more lightweight and easier to learn. Fun, even.

      If you want to understand unobtrusive javascripting (which is the only way to go really, unless you don't mind your site's content being invisible to search engines), PPK's book [quirksmode.org] is the best I've seen.
  • The majority of JavaScript books are of limited help in this regard, because they focus on the language details, illustrated only with code snippets. Many readers would benefit more from instruction via working examples, which is the approach used by The Book of JavaScript.

    Working examples - isn't that what the Internet is for? If I see something neat going on on someone's site, the first thing I generally do is to borrow the code. Also, why advertise this on SlashDot? If you didn't learn Javascript in

  • JavaScipt interfaces (Score:2, Interesting)

    by KickTheDog (583548)
    Yeah.. JavaScript is so much more powerful that people think. I went about designing a javascript ASP.NET DatePicker I ended up in the world of Object Orients JS... its a little different but with concepts like prototypes its amazing to what extent you build interfaces that can do almost anything the desktop can do. Dainty Date is open source and can be downloaded here http://www.customcontrolfreak.com/ [customcontrolfreak.com]

The world is no nursery. - Sigmund Freud

Working...