JavaScript: How Simple is Too Simple?

The following is republished from the Tech Times #167.

When we first sat down to write Simply JavaScript, Cameron and I had to decide how complicated we wanted to make things. On the one hand, this was to be a beginner’s book, so we wanted to keep things simple (it is called “Simply JavaScript”, after all).

On the other hand, JavaScript isn’t all that simple in the real world, and we felt too many other books were guilty of not giving their readers the tools they needed to understand and write real-world code. We didn’t want to make the same mistake of “dumbing down” the language to produce an easy-to-read book.

To show you what I mean, let’s throw together the same JavaScript example using code at several levels of complexity. The example will be a simple one: we’ll prompt the user to ask whether links to external sites should be opened in a new window. As we’ll see, however, even a simple example like this can get very complicated if you let it!

Simple but Ugly

If code simplicity were the ultimate goal, this example could be very simple indeed:

<a href="http://example.com/" onclick="
    if (confirm('Open this link in a new window?')) {
      window.open('http://example.com/');
      return false;
    }
">external link</a>

Let’s pause briefly while all the JavaScript veterans in the audience gouge their eyes out.

While this code will certainly work, and would be exceedingly easy to explain in a beginner’s JavaScript book, it’s a very messy solution to the problem. The code is sitting in the middle of the HTML content, and will have to be repeated for every link of this type on the page. Additionally, the URL of the link is repeated in the JavaScript code, which runs the risk of the two getting out of sync.

Still Too Simple?

The code snippet we saw above would have been considered cutting-edge sometime around 1997. Let’s see a more modern alternative that still attempts to keep things simple:

<a href="http://example.com/" class="ext">external link</a>
<script type="text/javascript">
  var links = document.getElementsByTagName("a");
  for (var i = 0; i < links.length; i++) {
    var link = links[i];
    if (link.className == "ext") {
      link.onclick = clickHandler;
    }
  }

  function clickHandler() {
    if (confirm("Open this link in a new window?")) {
      open(this.href);
      return false;
    }
  }

</script>

Rather than adding JavaScript code directly to every external link in the document, this version uses a single chunk of JavaScript code that detects all of the external links in the document (those with class="ext") and assigns the same JavaScript function (clickHandler) to handle the click event for each. This function can be shared between all the external links, because it uses this.href to fetch the URL to be opened from the link that has been clicked.

Many JavaScript books released in the past few years are content with the improvements that we made in this version of the script. The code is tidy enough, and it behaves as advertised. What more could a beginner ask for?

The problem with this thinking is that beginners who learn from examples like these go out into the wilds of the Web and find examples written using much more advanced JavaScript coding structures, and feel lost.

Simply Better

The main differences between the script we’ve just seen and the sort of code that web professionals are producing in the real world can be summed up in two words: unobtrusive scripting.

Unobtrusive scripting is the name given to a range of techniques that developers use to bundle up their JavaScript code so that it will not interfere with other scripts that may be in play on the same page. The script we have just seen, for example, would interfere with any other script that defined a function named clickHandler, or that registered a click event handler on the links of the page.

Because JavaScript is such a flexible language, there are many tricky ways to achieve unobtrusive scripting. Some popular methods add greatly to the complexity of writing even simple scripts, with references to variables and functions changing dramatically depending on where in the code they occur.

The challenge, when you’re writing a book like Simply JavaScript, is to show beginners how to write unobtrusive scripts without making the code too difficult for the novice programmer to grasp. Here’s what we came up with:

var ExternalLinks = {

  init: function() {
    var links = document.getElementsByTagName("a");
    for (var i = 0; i < links.length; i++) {
      var link = links[i];
      if (link.className == "ext") {
        Core.addEventListener(
          link, "click", ExternalLinks.clickHandler);
      }
    }
  },

  clickHandler: function(event) {
    if (confirm("Open this link in a new window?")) {
      open(this.href);
      Core.preventDefault(event);
    }
  }

};

Core.start(ExternalLinks);

The entire script is bundled up inside a JavaScript object called ExternalLinks, which is the only element of the script that could possibly clash with another script, and is consequently chosen to be rather unique. The script is made up of a collection of functions, which are defined as methods of this object.

This structure enables these functions to be called by the same name (e.g. ExternalLinks.clickHandler) wherever they may occur in your code.

Once the script is defined, the whole thing is kicked off by a call to its init method, which is triggered by the final line of the above code, Core.start(ExternalLinks);.

The problem of clashing event handlers is solved by the Core library of functions (Core.start, Core.addEventListener, Core.preventDefault, etc.), the inner workings of which are explained at appropriate points in the book.

While this approach lacks a few of the features of more sophisticated alternatives, it’s simple enough that beginners can grasp it and feel confident writing their own scripts following the same pattern. It also exposes them to more advanced language features like objects, so when the time comes that they need to adopt one of the more advanced coding styles, they stand a good chance of understanding the sample code they will find online.

By using this coding structure from the very first page, Simply JavaScript avoids teaching beginners bad habits. You also don’t get that awkward chapter that occurs around page 100 of several other recent JavaScript titles, where the author explains that the style of code presented up to that point in the book is flawed, and should be avoided.

A Unique Book

If a lot of the intricacies of JavaScript syntax discussed in this post went over your head, I apologize. I do hope, however, that you’ll consider picking up a copy of Simply JavaScript so that you can learn what you’ve been missing!

For those of you that know your JavaScript, I’d love to hear your thoughts on the approach to the language that we took. That, along with coverage of the major JavaScript libraries and our wacky sense of humor, is what makes this book so unique.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • 2MHost.com

    I believe that Javascript can’t be simple at all
    specially after reading this post :)

    your ‘unobtrusive scripting.’ solution is something can’t be handled by biggeners, the chance to make mistakes in such code is HUGE.

    Do you think that I’ll buy this book? YES, I’ll do.
    because I like the end of every chapter “Exploring Libraries”

    After using several libraries like Jquery and MooTools, I think they become mature enough to get book covering them in depth …. a little “javascript” and a lot of “Exploring Libraries”

  • Estelle

    Your argument is well thought out. Most javascript books are either too dumbed down and lead to bad code, or too advanced and impossible for the novice to follow.

    While I haven’t read your book, from your explanation as to how you approached presenting code, it seems that you will provide web developers at all levels of knowledge with enough information to code real world examples correctly. By introducing beginners to libraries, those novices will be able to quickly understand and perhaps even develop real world web applications.

    I’ll have to pick up a copy and get back to you on the approach.

    -Estelle

  • thenk83

    Kevin,
    I just received the book yesterday and I’m rather impressed. I’ve picked up more from this book than the Wrox, SAM Learn in 24hrs, and O’Reilly’s JavaScript beginner books. When I wanted to learn PHP, I picked up the PHP and MySQL book you published. I learned tons from that (in which I feel like I owe you because it’s basically launched a new career for me) one book, when others failed to keep it simple. I’ve really gotten the same feel with Simply JavaScript. Thanks for another awesome book. Oh, and better its very structured in the way coding and learning should be laid out.

  • loganathan

    i like the simple tricks in the book …ofcourse the article is really impressive

  • zee

    Examples in the book simply javascript uses some core library but I didn’t find any mention of where to get it or if it’s required.

    The first real sample doesn’t work.

    I would expect this info in preface.