about this book

JavaScript is important. That wasn’t always so, but it’s true now.

Web applications are expected to give users a rich user interface experience, and without JavaScript, you might as well just be showing pictures of kittens. More than ever, web developers need to have a sound grasp of the language that brings life to web applications.

And like orange juice and breakfast, JavaScript isn’t just for browsers anymore. The language has knocked down the walls of the browser and is being used on the server in engines such as Rhino and V8, and in frameworks like Node.js.

Although this book is primarily focused on JavaScript for web applications, the fundamentals of the language presented in part 2 of this book are applicable across the board.

With more and more developers using JavaScript, it’s now more important than ever that they grasp its fundamentals, so that they can become true ninjas of the language.

Audience

This is not your first JavaScript book. If you’re a complete novice to JavaScript, or you only understand a handful of statements by searching the web for code snippets, this is not the book for you. Yet.

This book is aimed at web developers who already have at least a basic grasp of JavaScript. You should understand the basic structure of JavaScript statements and how they work to create straightforward on-page scripts. You don’t need to be an advanced user of the language—that’s what this book is for—but you shouldn’t be a rank novice.

You should also have a working knowledge of HTML and CSS. Again, nothing too advanced, but you should know the basics of putting a web page together.

If you want some good prerequisite material, grab one of the popular books on JavaScript and web development, and then tackle this one. We can recommend JavaScript: The Definitive Guide by David Flanagan, JavaScript: The Good Parts by Douglas Crockford, and Head First JavaScript by Michael Morrison.

Roadmap

This book is organized to take you from an apprentice to a ninja in four parts.

Part 1 introduces the topic and some tools we’ll need as we progress through the rest of the book.

Part 2 focuses on JavaScript fundamentals: aspects of the language that you take for granted but aren’t really sure how they work. This may be the most important part of the book, and even if it’s all you read, you’ll come away with a much sounder understanding of JavaScript, the language.

In part 3, we dive into using the fundamentals that we learned in part 2 to solve knotty problems that the browsers throw at us.

Part 4 wraps up the book with a look at advanced topics focusing on lessons learned from the creation of advanced JavaScript libraries, such as jQuery.

Let’s take a brief look at what each chapter will cover.

Chapter 1 introduces us to the challenges that we face as writers of advanced web applications. It presents some of the problems that the proliferation of browsers creates, and suggests best current practices that we should follow when developing our applications, including testing and performance analysis.

Chapter 2 discusses testing, taking a look at the current state of testing and test tools. It also introduces a small but powerful testing concept, the assert, which will be used extensively throughout the remainder of the book to make sure that our code does what we think it should be doing (or sometimes to prove that it doesn’t!).

Armed with these tools, chapter 3 begins our foray into the fundamentals of the language, starting, perhaps to your surprise, with a thorough examination of the function as defined by JavaScript. Although you might have expected the object to be the target of first focus, it’s a solid understanding of the function, and JavaScript as a functional language, that begins our transformation from run-of-the-mill JavaScript coders to JavaScript ninjas!

Not being done with functions quite yet, chapter 4 takes the fundamentals we learned in chapter 3 and applies them to problems we face in creating our applications. We’ll explore recursion—not only for its own sake, but because we can learn a lot more about functions through scrutinizing it—and we’ll learn how the functional programming aspects of JavaScript can be applied to not only make our code elegant, but also more robust and succinct. We’ll learn ways to deal with variable argument lists, and ways to overload functions in a language that doesn’t natively support the object-oriented concept of method overloading.

One of the most important concepts you can take away from this book is the subject of chapter 5: closures. A key concept in functional programming, closures allow us to exert fine-grained control over the scope of objects that we declare and create in our programs. The control of these scopes is the key factor in writing code worthy of a ninja. Even if you stop reading after this chapter (but we hope that you don’t), you’ll be a far better JavaScript developer than when you started.

Objects are finally addressed in chapter 6, where we learn how patterns of objects can be created through the prototype property of the function, and we’ll learn how objects are tied to functions for their definitions—one of the many reasons we discussed functions first.

Chapter 7 focuses on the regular expression, an often-overlooked feature of the language that can do the work of scores of lines of code when used correctly. We’ll learn how to construct and use regular expressions and how to solve some recurring problems elegantly, using regular expressions and the methods that work with them.

Part 2 on language fundamentals closes out with chapter 8, in which we learn how timers and intervals work in the single-threaded nature of JavaScript. HTML5 promises to bring us relief from the confines of the single thread with web workers, but most browsers aren’t quite there yet, and virtually all of the existing JavaScript code depends upon a good understanding of JavaScript’s single-threaded model.

Part 3 opens with chapter 9, in which we open the black box of JavaScript’s runtime code evaluation. We’ll look at various ways to evaluate code on the fly, including how to do so safely and in the scope of our choosing. Real-world examples, such as JSON evaluation, metalanguages (a.k.a. domain-specific languages), compression and obfuscation, and even aspect-oriented programming, are discussed.

In chapter 10, we examine the controversial with statement, which is used to shorten references within a scope. Whether you are a fan or detractor of with, it exists in a lot of code in the wild, and you should understand it regardless of whether you think it’s the bomb or an abomination.

Dealing with cross-browser issues is the subject of chapter 11. We examine the five key development concerns with regard to these issues: browser differences, bugs and bug fixes, external code and markup, missing features, and regressions. Strategies such as feature simulation and object detection are discussed at length to help us deal with these cross-browser challenges.

Handling element attributes, properties, and styles is the focus of chapter 12. While the differences in how the various browsers handle these aspects of elements are slowly converging over time, there still exists a number of knotty problems that this chapter describes how to solve.

Part 3 concludes in chapter 13 with a thorough investigation of event handling in the browsers and ways to create a unified subsystem that handles events in a browser-agnostic manner. This includes adding features not provided by the browsers, such as custom events and event delegation.

In part 4 we pick up the pace and delve deeply into advanced topics taken from the heart of JavaScript libraries such as jQuery. Chapter 14 discusses how DOM manipulation APIs can be constructed to manipulate the Document Object Model at runtime, including the Gordian knot of injecting new elements into the DOM.

Finally, in chapter 15, we discuss how CSS selector engines are constructed and the different ways in which they parse and evaluate selectors. Not for the faint of heart, this chapter, but it’s a worthy final test of your ninja-hood.

Code conventions

All source code in listings or in the text is in a fixed-width font like this to separate it from ordinary text. Method and function names, properties, XML elements, and attributes in the text are also presented in this same font.

In some cases, the original source code has been reformatted to fit on the pages. In general, the original code was written with page-width limitations in mind, but sometimes you may find a slight formatting difference between the code in the book and that provided in the source download. In a few rare cases, where long lines could not be reformatted without changing their meaning, the book listings contain line-continuation markers.

Code annotations accompany many of the listings, highlighting important concepts. In many cases, numbered bullets link to explanations that follow in the text.

Code downloads

Source code for all the working examples in this book (along with some extras that never made it into the text) is available for download from the book’s web page at www.manning.com/SecretsoftheJavaScriptNinja.

The code examples for this book are organized by chapter, with separate folders for each chapter. The layout is ready to be served by a local web server, such as the Apache HTTP Server. Simply unzip the downloaded code into a folder of your choice and make that folder the document root of the application.

With a few exceptions, most of the examples don’t require the presence of a web server at all and can be loaded directly into a browser for execution, if you so desire.

All examples were tested in a variety of modern browsers (as of mid-2012), including Internet Explorer 9, Firefox, Safari, and Google Chrome.

Author online

The authors and Manning Publications invite you to the book’s forum, run by Manning Publications, where you can make comments about the book, ask technical questions, and receive help from the authors and other users. To access and subscribe to the forum, point your browser to www.manning.com/SecretsoftheJavaScriptNinja and click the Author Online link. This page provides information on how to get on the forum once you are registered, what kind of help is available, and the rules of conduct in the forum.

Manning’s commitment to our readers is to provide a venue where a meaningful dialogue between individual readers and between readers and the authors can take place. It’s not a commitment to any specific amount of participation on the part of the authors, whose contribution to the book’s forum remains voluntary (and unpaid). We suggest you try asking the authors some challenging questions, lest their interest stray!

The Author Online forum and the archives of previous discussions will be accessible from the publisher’s website as long as the book is in print.

About the cover illustration

The figure on the cover of Secrets of the JavaScript Ninja is captioned “Noh Actor, Samurai,” from a woodblock print by an unknown Japanese artist of the mid-nineteenth century. Derived from the Japanese word for talent or skill, Noh is a form of classical Japanese musical drama that has been performed since the 14th century. Many characters are masked, with men playing male and female roles. The samurai, a hero figure in Japan for hundreds of years, was often featured in the performances, and in this print the artist renders with great skill the beauty of the costume and the ferocity of the samurai.

Samurai and ninjas were both warriors excelling in the Japanese art of war, known for their bravery and cunning. Samurai were elite soldiers, well-educated men who knew how to read and write as well as fight, and they were bound by a strict code of honor called Bushido (The Way of the Warrior), which was passed down orally from generation to generation, starting in the 10th century. Recruited from the aristocracy and upper classes, analagous to European knights, samurai went into battle in large formations, wearing elaborate armor and colorful dress meant to impress and intimidate. Ninjas were chosen for their martial arts skills rather than their social standing or education. Dressed in black and with their faces covered, they were sent on missions alone or in small groups to attack the enemy with subterfuge and stealth, using any tactics to assure success; their only code was one of secrecy.

The cover illustration is from a set of three Japanes prints owned for many years by a Manning editor, and when we were looking for a ninja for the cover of this book, the striking samurai print came to our attention and was selected for its intricate details, vibrant colors, and vivid depiction of a ferocious warrior ready to strike—and win.

At a time when it is hard to tell one computer book from another, Manning celebrates the inventiveness and initiative of the computer business with book covers based on two-hundred-year-old illustrations that depict the rich diversity of traditional costumes from around the world, brought back to life by prints such as this one.