Stories
Slash Boxes
Comments

News for nerds, stuff that matters

Slashdot Log In

Log In

Create Account  |  Retrieve Password

JavaScript: The Good Parts

Posted by samzenpus on Fri Jul 25, 2008 12:55 PM
from the read-all-about-it dept.
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.
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.
+ -
story
This discussion has been archived. No new comments can be posted.
The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
 Full
 Abbreviated
 Hidden
More
Loading... please wait.
  • by WED Fan (911325) <akahige AT trashmail DOT net> on Friday July 25 2008, @01:06PM (#24338577) Homepage Journal

    Javascript has its uses and works fine. Platforms have been the problem for me in the past. But with new libraries like jQuery, Javascript has become quite the tool.

    • by RandoX (828285) on Friday July 25 2008, @01:16PM (#24338793)

      Why would anyone need anything other than VBScript for client-side web scripting? :)

      • Re: (Score:3, Interesting)

        by edmicman (830206)
        Ugh....we've inherited a site that does just that. Granted, we run a classic ASP main site that uses VBScript on the server side, but I never even know there was client-side VBScript. Their whole damn website is non-functional in anything but IE...hell, they even have corresponding Javascript in some of the pages commented out, replaced by clientside VBScript!
  • One browser? (Score:4, Informative)

    by Benbrizzi (1295505) on Friday July 25 2008, @01:11PM (#24338687)

    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.

    • Re:One browser? (Score:5, Informative)

      by xactoguy (555443) on Friday July 25 2008, @01:27PM (#24338995)
      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.
    • Re:One browser? (Score:5, Informative)

      by Bogtha (906264) on Friday July 25 2008, @01:27PM (#24338997)

      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.

      • Re: (Score:3, Interesting)

        by Joebert (946227)

        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.

        Not to mention applications like Adobe Fireworks, Flash, Photoshop, 7 a whole host of other applications utilize Javascript for extensions. Lookup "JSF" with Macromedia or Adobe context for more on that.
        Some Apple applications use both Applescript & Javascript

        • At the very least, display an error telling me that the site only works with JavaScript enabled! I can't believe how lazy (or is it stupid?) some developers are. How long would it take to stick a piece of text in there that you immediately hide with javascript?

        • by Bogtha (906264)

          Call me flamebait or troll if you wish, but facts are facts. It is dangerous to be so trusting and most Flash is just a waste of bandwith especially to those customers furthest from the big stores and stuck on dialup.

          Okay, you're a troll. What does checking in Firefox have to do with server-side or desktop JavaScript that isn't even designed to run in a browser? What "trust" do you think is dangerous here and what does your opinion of Flash being a waste of bandwidth have to do with it?

        • Re: (Score:3, Interesting)

          by Bogtha (906264)

          You don't need more than one browser to write a JavaScript program, you need more than one browser to develop a website.

          This is a red herring as webites are not the topic

          How can it be a "red herring"? What do you even mean by that? If you are talking about browser testing, you are talking about websites. I was pointing out that multi-browser testing isn't as mandatory as Benbrizzi claims because browsers aren't the only place that JavaScript is used.

          To display anything at all with javascript requ

            • Re: (Score:3, Informative)

              by Bogtha (906264)

              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 n

    • Re:One browser? (Score:4, Informative)

      by uhlume (597871) on Friday July 25 2008, @01:37PM (#24339175) Homepage

      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.

    • To be more precise, I suppose you meant that there are still many cross-browser incompatibilities with DOM, CSS and HTML, not on the javascript language itself, isn't it ?

      • Re: (Score:2, Insightful)

        Yes, but if you are going to code something, code it for Firefox. Firefox is enough standards-compliant that more strict browsers (such as Safari and Opera) can usually read JavaScript for Firefox. Leave out IE till the end, because likely it will give you more headaches then it is worth. Plus, IE is only written for 1 platform (Windows) and also, IE becomes more standards supporting with each release, but still proprietary enough to make it an absolute pain to code anything for it.
          • Re:One browser? (Score:4, Insightful)

            by Poltras (680608) on Friday July 25 2008, @03:43PM (#24341103) Homepage

            Stop confusing C# with .Net, stop confusing Obj-C with Cocoa, stop confusing C++ with STL. Stop confusing C with stdlib. Stop confusing COBOL with mainframe.

            Yes, a language and an API are unrelated, but I've rarely seen one without the other. Have you seen many javascript running outside web browsers lately? And while you are correct that you don't have to learn DOM to get into Javascript, you'll need it sooner than later, and using a coherent/compliant implementation of it is crucial in its learning.

            • Re:One browser? (Score:4, Interesting)

              by zoips (576749) on Friday July 25 2008, @04:22PM (#24341747) Homepage
              Yes, I have. At my last job basically our entire test framework was written in Javascript. Why, I'm not sure, but it was. I also do most of my scripting in Javascript and execute using Rhino. If it's not going fast enough, I just use Rhino to compile it all to Java bytecode and execute it directly in the JVM.

              As I said elsewhere in this thread, just because Javascript is widely used for browser scripting, does not mean that is its only use. Your blurb at the beginning is completely irrelevant to this topic.
  • is its neigbhorhood, where it is used. you spend 90% of your programming time dealing with the quirks between different browsers. ie isn't even the biggest offender, safari is

    which is to say, there is nothing wrong with javascript. it a diamond trapped in a cage made out of shit

    • ie isn't even the biggest offender, safari is

      Depends on whether you are developing on Safari or on IE, doesn't it? :)

      I actually use Firefox for the initial development and then test/fix for the others. Since I've started using jQuery, I spend a lot less time fixing stuff between browsers.

      • fuck safari (Score:3, Interesting)

        i just wrote some script to handle anchor tag clicks globally. firefox, fine. opera, fine. ie, fine. safari: doesn't work in safari, because safari insists on doing the default action no matter what

        http://codingforums.com/archive/index.php?t-30983.html [codingforums.com]

        you can't cancel dom events in safari! fuck safari. so now i have to completely write off safari support, or completely alter my programming model because of its stupidity, and do some really guly hacks

        or perhaps, no hacks possible!:

        http://www.peterblum.com/Sa [peterblum.com]

        • browser fucking (Score:4, Informative)

          by MightyYar (622222) on Friday July 25 2008, @02:37PM (#24340109)

          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.

            • by Fweeky (41046) on Saturday July 26 2008, @05:06AM (#24346785) Homepage

              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.

              • its simple (Score:3, 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 ;-(

                • Re: (Score:3, Insightful)

                  by Phroggy (441)

                  do i give up all of my work and program from scratch according to a new approach? or do i just ignore safari?

                  That depends. Starting from scratch with a new approach might result in code that's even more compatible with other browsers you haven't thought of, and it might even work better on the browsers you already do support.

                  Not only does the iPhone use WebKit, but my Nokia phone does as well. How many mobile users access your web site?

    • Re: (Score:3, 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 tha

      • by Pollardito (781263) on Friday July 25 2008, @09:17PM (#24344837)
        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.
  • by Shaitan Apistos (1104613) on Friday July 25 2008, @01:21PM (#24338897)

    ...of a t-shirt I saw once, it read "But what about all the good things Hitler did."

    In all seriousness though with Prototype I don't find javascript browser inconsistencies nearly as problematic as css browser inconsistencies.

    • Re: (Score:3, Interesting)

      by Tumbleweed (3706) *

      In all seriousness though with Prototype I don't find javascript browser inconsistencies nearly as problematic as css browser inconsistencies.

      Yeah, wait until you start using javascript to manipulate css, the you get the best of both worlds (of pain).

  • I love JavaScript :)

    Am I a crazy mad man?

  • [html]
    [head]
    [/head]

    [body]

    [script type="text/javascript"]
    document.write("This message is written by JavaScript");
    [/script]

                    Here?
    [/body]
    [/html]

  • Scoping is Awful? (Score:4, Informative)

    by PipianJ (574459) on Friday July 25 2008, @01:31PM (#24339091)

    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);

    • I recommend buying the book. Closures are implemented with the expected scoping. They allow you do to things like this:

      function createCounter()
      {
      var i = 0;
      return {
      incr: function() { ++i; },
      decr: function() { --i; },
      getValue: function() { return i; }
      }
      }
      • Re: (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).

  • TiddlyWiki (Score:2, Interesting)

    by yumyum (168683)

    To see some incredible (IMO) JavaScript functionality, check out TiddlyWiki [tiddlywiki.com].

  • I can tell from the title alone that this has got to be the shortest book ever written.
  • The author's website (Score:5, Informative)

    by DCstewieG (824956) on Friday July 25 2008, @01:49PM (#24339363)

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

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

  • by spads (1095039) on Friday July 25 2008, @02:50PM (#24340307)
    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/ [crockford.com], http://yuiblog.com/blog/2007/01/24/video-crockford-tjpl/ [yuiblog.com]) are, I would consider checking this one out.
  • Well Written (Score:4, Insightful)

    by MrMunkey (1039894) on Friday July 25 2008, @03:15PM (#24340641) Homepage
    I've had the book for about a month now. I've read most of it, but I haven't finished it yet due to work and personal projects and tv and games... Anyway, I think it is really well written. Doug is definitely has a very intimate knowledge of the subject, but his writing comes across more like a guide than an expert. He takes an approach kind of like taking you on a tour of the language. It's a pretty short book, so in theory it should be a quick read. I'd suggest you pick it up if even for only understanding JavaScript better.
  • by metafizzical (1203436) on Friday July 25 2008, @04:54PM (#24342171)

    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 [jslint.com] 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.

      • function itsPossible () {
                var itsPossible = document.createElement('div');
                itsPossible.appendChild(document.createTextNode('It&apos;s possible'));
                document.body.insertBefore(itsPossible, document.body.childNodes[0]);
        )

        itsPossible();

          • Re:No (Score:5, Funny)

            by Anonymous Coward on Friday July 25 2008, @01:53PM (#24339425)

            Four spaces baby; the way God indented.

    • I tend to think of programming languages the same way I do hammers; they're tools to be used to accomplish a goal. That being said, I have to say I've always found Smalltalk to be a very cool language.

    • Since when is ANY programming language "cool"?

      I myself don't find JavaScript cool, but I couldn't say the same about Prolog, Forth or LUA. On top of that, INTERCAL and LOLCODE also manage to be funny. ;-)

      On a more serious note, if you can "feel" something as uncool, others can feel them as cool. Feeling nothing translates into perfect indifference. And since you posted a comment, your post itself is proof that inanimate tools do cause emotions and sentiments, your own words notwithstanding.

    • maybe not cool in the sense of popularity by the people world as a whole... But by that sense, not much, if anything, is 'cool'. In the popularity sense, 'cool' tends to be geared towards a culture or grouping. Be it Americans, western culture, eastern culture, Russians, British, business executives, geeks... The slang word cool tends to be used in a rather flexible manner.

      Also, it's a word rooted in OPPINION, which means SUBJECTIVE and not OBJECTIVE. That's probably related to the relative-to-grouping conc

    • It is a very short book (I actually own it). However, if you have to use JS - it is an excellent resource. There is a section on the Bad Parts too - there isn't much detail in the Bad Parts, but it is still a hefty portion of the book.