JOHN PELOQUIN is a software engineer with over 10 years of JavaScript experience ranging across applications of all sizes. John earned his B.A. in Mathematics from U.C. Berkeley and is currently a lead engineer at Spreemo, a healthcare technology startup in NYC. Prior to editing this volume, John edited Professional Website Performance by Peter Smith (Wiley 2012) and Professional JavaScript for Web Developers, 3rd ed. by Nicholas Zakas (Wiley 2012). When he is not coding or collecting errata, John can occasionally be found doing stand-up comedy at an open mic.
ACKNOWLEDGMENTS
Thank you to my wife, Bethany, for her love and support while we wrote this book, and for enduring (or enjoying?) many husband-less nights and weekends while I worked to meet a deadline.
Thanks to my family for encouraging me to pursue my dreams. My dreams may include writing a book, but they begin and end with you.
This book would not have been possible without the willingness of others to share their knowledge and expertise with us and the community at large in book, blog, and source-code format. Together, we'd like to acknowledge and thank:
● Douglas Crockford, for his exposure of good parts of JavaScript and his work on jsLint.
● Nicolas Zakas, for the numerous books and blog posts he wrote that acted as guides through JavaScript's sometimes-treacherous waters, and also his maintenance of and contributions to ESLint.
● Stoyan Stefanov, for his instruction on applying pattern-based development to JavaScript.
● Robert C. Martin, for instilling in us the desire to write clean code.
● Fredrik Appelberg, for his creation of, and Dave Clayton for his contributions to, the AOP.js aspect-oriented programming framework.
● Mike Bostock, for inspiring us with the D3 library for SVG graphics.
● The folks at Pivotal Labs, for the creation of the open-source JavaScript framework Jasmine, and members of the community that have contributed to the framework.
● The AngularJS team, for showing the world a great way to build single-page applications.
● The vast and growing network of generous people on sites such as Stack Overflow and GitHub. Without you, we'd still be thumbing through manuals.
We would also like to express our appreciation to our project editor, Chris Haviland, who deftly maneuvered us through the writing process from beginning to end. Our copy editor, Nancy Rapoport, has read our book more carefully, and more times, than anyone else ever will. For her dedication and suggestions we offer heartfelt thanks. We would also like to express our sincerest thanks to our technical editors, Keith Pepin and John Peloquin. Their JavaScript prowess helped us avoid more than a few technical errors. Should any errors still exist, it's likely because we didn't follow some of their advice. Our hats are off to you, gentlemen.
Finally, we'd like to thank Carol Long, the Executive Acquisitions Editor at Wiley, who gave us the opportunity to write this book. Without her, we'd still just be a couple of guys that write software for a living. We're still that, but now we're authors, too. Carol announced her retirement from the publishing industry just before we finished the book. We sure hope we weren't the straw that broke the camel's back! Thank you, Carol, and we wish you nothing but sunny days and margaritas in your retirement.
INTRODUCTION
WHEN WE SHARED THE TITLE OF THIS BOOK, Reliable JavaScript, with fellow developers, we received feedback such as:
“Now there's a juxtaposition!”
“It must be a very short book.”
“Will I find it next to the latest John Grisham thriller in the fiction section of the bookstore?”
No, this book is not a work of fiction.
The feedback we received about the title of the book illustrates a broader perception about JavaScript that some developers with experience in classical, compiled languages have: JavaScript is used to create flashy portfolio websites or simple to-do apps; it has no business in my mission-critical enterprise application.
In the past that was true, but no more.
THE RISE OF JAVASCRIPT AS A FIRST-CLASS LANGUAGE
JavaScript's reputation as a wild child is well-deserved, and we hope to amuse you with some of its exploits in the next two sections. However, like a spoiled heiress who inherits the family business and surprises everyone by rising to the challenge, she has turned serious and responsible, lately showing herself capable of true greatness.
Her early life was as a dilettante, rarely entrusted with anything more than short “scripting” tasks. The decisions she made were simple: If a required field was not filled in, she should color it red; if a button was clicked, she should bring another page into view. Although her responsibilities were limited, she was easy to get along with and made many friends. To this day, most programmers' experience of her is primarily of this sort.
Then, in the shift that was to redefine her life, the world turned to the web. This had been her playground, her little place to amuse herself while members of The Old Boys Club did the real work on the server.
The wave started to break in the late 1990s when Microsoft introduced first iframes and then XMLHTTP. When Google made Ajax part of its Gmail application in 2004 and Google Maps in 2005, the wave came crashing down. The world was suddenly aware of just how much richer the web experience could be when the browser was entrusted with more than just displaying whatever the server dispensed.
So it was that our princess was given more responsibility than anyone had ever intended. She would need help.
And help did come, in the form of toolkits and frameworks like jQuery, Ext JS, Ember.js, Knockout, Backbone, and AngularJS. These worthy advisors did everything they could to bring discipline and structure to JavaScript. However, they never quite tamed her youthful exuberance. In spite of her advisors and her good intentions, she was always getting into trouble.
THE EASE OF WRITING TRULY DISASTROUS CODE IN JAVASCRIPT
Part of the problem, which she has only recently begun to outgrow, was her years spent as a page-scripting language. In that limited sphere, there was no harm in making a variable or function global. If a variable was misspelled, the effects were limited and easy to track down. (By the way, the effect would likely be to create yet another global.) If the architecture was sloppy.. well, how much architecture can there even be on just one web page?
Compounding the potential for error was the lack of a compiler. Server-side programs in C# or Java are guaranteed to be at least syntactically correct before they are run. JavaScript must start and hope for the best. A misspelled variable, or a call to a non-existent function, can lurk in the code for months until a particular execution path is followed.
And then there are the quirks. Ah, those endearing, maddening quirks.
At the top of the list must be the distinction between ==
(equality with type coercion) and ===
(without). A great idea, but so hard for programmers primarily trained in other languages to get used to!
Never is JavaScript more coquettish than when it comes to truth and falsehood. She has a notion of “truthy” and “falsy” that confuses all but the most determined suitors. Zero is a falsy value so, thanks to type coercion, the expression
is true
. But not for the reason you think. The value false
is coerced to a number, which is 0
(true
would convert to 1
). Next, the string '0'
is also coerced to a number. That is also 0
, so the result is true
.
However,