O'Reilly logo

JavaScript Cookbook, 2nd Edition by Shelley Powers

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The World of JavaScript

I wrote my first book on JavaScript in 1996. At the time, we had to really dig to fill the book. This was before DHTML, before ECMAScript, before mobile development, and definitely before Node.js. Form validation and popping up alerts were the big things. With this second edition of the JavaScript Cookbook, I had the opposite problem: the world of JavaScript is just too immense to stuff into one book. But I gave it my all.

The world of JavaScript is the key to this book. The use of JavaScript has expanded from the browser to the server, to the mobile environment, to the cloud. We’ve gone beyond simple libraries to complex modular systems; from basic animations to rich data visualizations, with a little audio and video tossed in for fun and giggles. Entire applications are served in one HTML page thanks to sophisticated frameworks, and MEAN is no longer an adjective to apply to nasty folk.

Ajax is still around and still relevant, but now it’s joined by direct and immediate bidirectional communication—no more having to fake server-client communication, because we have it, for real. We can connect to Twitter and Dropbox, create apps for Android devices, and open ePub files directly in the browser for reading. The libraries and modules available in both the client and server take care of so much of the complex, tedious bits, that we can focus on creating what’s unique to our applications. Ten years ago, we’d be surprised at finding a library that met our needs. Now, we’re surprised when we don’t.

We have all of this, but we still have JavaScript, the language. We still have String and Number, Array and Function, and the most basic of statements:

var someVar = 'Hello, World?';

However, today’s JavaScript is not the same as the language I first wrote about in 1996. It’s growing and expanding, with ECMAScript 5, and now ECMAScript 6, and even the newest additions for ECMAScript 7. It seem as if there’s a new addition to the language every month. What am I saying…there is a new edition every month.

Just to make it even more interesting and rich is the increasing number of APIs provided by both standards organizations and sevice providers.

There’s never been a more exciting time to be a JavaScript developer. But it can also be a little overwhelming, and that’s the focus of this book: getting a handle on this big wonderful world of JavaScript.

Book Audience

In order to encompass the many subjects and topics reflective of JavaScript in use today, we had to start with one premise: this is not a book for a JavaScript newbie. There are so many good books and tutorials for those new to JavaScript that we felt comfortable setting the bar a little higher than the first edition of the JavaScript Cookbook.

If you’ve been playing around with JavaScript for several months, maybe tried your hand with a little Node or Ajax development, you should be comfortable with the book material. Some of the subjects might be challenging, but in a good way.

Book Architecture or Why Is This Book Organized in This Way?

I originally had this idea of a large graphic diagramming the world of JavaScript, which I would split into fragments, which I would then use to introduce each chapter. It didn’t take long for me to realize that no component of JavaScript exists in isolation from the others. If anything, JavaScript is one big Venn diagram, with dozens of intersections—more of a spirograph than distinct, connected bubbles. So much for grand visualizations. Instead, I split the book into 18 loosely defined chapters, with overlap handled by cross references.

The book is split into two parts labeled Classic JavaScript and JavaScript, All Blown Up.

The classic parts of JavaScript are the solid foundations of the language we’ve had for the last decade, and aren’t going away. But they aren’t standing still, either. We have our friends String, Number, Boolean, Array, Function, and Object, but thanks to ECMAScript 5 and 6, there’s a lot more we can do with these objects. In addition, before we can get into the more leading-edge, complex uses of JavaScript, we still need to understand how to use Ajax, work with JSON, create and use libraries, as well as incorporate one of the more popular (jQuery) into our applications. We also need to understand how to work within the browser, which is still the working environment for most JavaScript development, as well as test our creations and make sure they’re accessible.

Now that video and audio, as well as the Canvas element and SVG, are supported in all modern browsers, a basic understanding of these rich media elements is fundamental.

The All Blown Up part of JavaScript is basically everything else. This includes the new objects introduced in ECMAScript 6, JavaScript in the server (Node), complex frameworks (in the server and client), and modular JavaScript. It also includes JavaScript in mobile devices, data visualizatons, graphical tools available in the server, bidirectional client-server communication, and the rich world of available APIs, libraries, and modules.

It seems a bewildering mess at times, but the more examples you try in the different environments, the more you realize that JavaScript is the key that makes it all come together.

A break down of the chapters follows in the next sections.

Part I, Classic JavaScript

Part I focuses on traditional uses of JavaScript as they’ve been practiced the last several years, but updated to incorporate new ideas, modifications, and improved functionality:

Chapter 1, The JavaScript Not-So-Simple Building Blocks
Covering use of some familiar old friends: String, Number, Boolean, RegExp, Math, and Date. The coverage goes beyond the basic, and also touches on some of the new extensions that come to us via ECMAScript 5 and 6.
Chapter 2, JavaScript Arrays
Probably no component of JavaScript, the language, has changed more than the simple, essential Array. This chapter goes beyond basic Array use, and covers some of the newer functionality.
Chapter 3, Functions: The JavaScript Building Blocks
The ubiquitous Function—what would we do without it? In JavaScript, very little. This chapter covers some of the more advanced function uses, and introduces more modern functional uses. We’ll look at the three basic function construction types, as well as the extremely useful IIFE (Immediately Invoked Function Expression).
Chapter 4, The Malleable JavaScript Object
Following closely on the heels of the Array in undergoing change, both in perception and use, the JavaScript Object is nothing if not malleable, hence the chapter title. Most of the chapter focuses on this malleability, both the good uses and the not as good. I also briefly touch on the increasing popularity of functional programming versus object-oriented.
Chapter 5, JavaScript and Directly Accessing the User Interface
You can’t escape the DOM, the DOM knows all (nless it’s Shadow DOM, covered in Chapter 14). It’s a whole lot more fun to work with the DOM nowadays, thanks to new querying capabilitiy. And though most folks use jQuery, it’s still important to understand what’s happening beneath the surface of this and other popular libraries.
Chapter 6, Preliminary Testing and Accessibility
No matter how new JavaScript is, there are still JavaScript best practices to follow, such as keeping our code clean, testing, and ensuring accessibility. We now have new tools to make these necessary tasks a little easier, and a little more entertaining.
Chapter 7, Creating and Using JavaScript Libraries
Here we’ll look at the basics of library creation, including minification, hosting your library in GitHub or CDN, using external libraries (jQuery and Underscore), and converting your library to a jQuery plug-in. We’ll take jQuery for a spin, but not all libraries do all things—we’ll also take a look at libraries that focus on one single type of task. Once we have the basics of library building under our belt, we can continue with modularizing our code, in Chapter 12.
Chapter 8, Simplified Client-Server Communication and Data
You can’t play with the new communication techniques (e.g. WebSockets) without a good understanding of Ajax, as well as how to work with JSON and XML. Yes, XML still does exist. Understanding the technology covered in this chapter is necessary before working with the newer client-server communication covered in Chapter 14.
Chapter 9, Creating Media Rich, Interactive Web Effects
This chapter provides basic usage techniques for the Canvas element and 2D graphics, SVG, and the audio and video elements. It also touches on combining the media types (integrating SVG and Canvas) and altering videos as they run. Data visualizations, more escoteric graphical tools, and server-side graphics are covered in Chapter 16.

Part II, JavaScript, All Blown Up

Part II is labeled All Blown Up because a few years ago, JavaScript developers never could have imagined all the things we can do today. Not all of the technology covered is brand new, but most is leading-edge. This part of the book also gets into the more complex uses of JavaScript, such as advanced client-server communication, data visualization, OAuth, and mobile development:

Chapter 10, The New ECMAScript Standard Objects
There are several new objects introduced with ECMAScript 6. I touch on all of them, or at least, all of them known at the time the book was written. (Yes, JavaScript is changing…a bit too fast to keep up with, at times.) What’s my favorite new additions? Function generators and iterators.
Chapter 11, Node: JavaScript on the Server
This chapter provides a faster paced introduction to working with Node.js. You don’t need past experience with Node to work with the examples in this chapter, but the chapter does move along quickly. It also answers those most commonly asked Node questions: How do you keep a Node server running; how do you run Node on the same server as Apache; how do you automatically restart Node when the application changes, or it goes down for some reason. It also explores how to use Node modules, and how to create a stand alone application based on Node.
Chapter 12, Modularizing and Managing JavaScript
This chapter is all about the new world of JavaScript modularization. It takes the older but still necessary components of code reuse, covered in Chapter 7, and incorporates the many new tools and approaches for creating, distributing, and using modular code. The chapter introduces the different approaches to modularization (AMD and Common JS), creating Node modules, working with RequireJS, Bower, Browserify, and that task master, Grunt. We in JavaScript are nothing if not creative with our application names.
Chapter 13, Fun with APIs
An API is a programmer contract. It’s an interface into the inner working of the browser, but it’s also a way of accessing services or data from a media server or remote resource. APIs are also used in graphical, data, and mobile applications, covered in Chapters 16 through 18. This chapter introduces three different kinds of APIs: remote APIs built on the principle of REST, new W3C APIs that introduce us to new capabilities in the browser, and remote APIs that act locally.
Chapter 14, JavaScript Frameworks

Some of the more complex JavaScript components are the frameworks, whether they’re located on the server (ExpressJS), or in the client (AngularJS, Backbone, or Ember). Frameworks also encompass complex strategies for certain problems or business use, like OAuth for authorization, and the very new Web Components.

A few asides about this chapter before moving on: I wanted to include a demonstration of at least one of the popular client-side MV* framework tools in the book, but couldn’t decide which one. They do differ enough that covering one results in recipes that aren’t helpful for folks not using that specific framework. That’s when I decided on deconstructing the ToDoMVC web application, and diving into how it’s implemented using three of the more popular framework tools: Angular, Ember.js, and Backbone. Hopefully, the process I used can be used with the other frameworks.

I did go into much more depth with the OAuth framework, because of its increasing use authorizing access for data and services at the many APIs we’re interested in using. OAuth is also used with the Twitter API, covered in Chapter 13, as well as the Dropbox Datastores, covered in Chapter 17.

I also covered Web Components, but without reliance on a polyfill (e.g. Google’s Polymer), as I’m wary of replying on roprietary technology when learning about something new.

Chapter 15, Advanced Client-Server Communications and Streams
Client-server communications is so much better now that WebSockets and CORS (Cross-Origin Resource Sharing) are standard in all modern browsers. Real-time, bidirectional communication can greatly simplify our lives. And because this type of communication is a stream, this chapter also takes a look at Node’s new transform streams.
Chapter 16, Data Visualizations and Client/Server Graphics

Some of the graphical applications we had fun with when the Canvas element and SVG first received broader support are giving way to more serious data visualizations, most of which use data provided directly from the server. This chapter takes a closer look at data visualization tools, including one that partners with a WebSocket server application.

Speaking of the server, we now have access to the same rich visualization and graphics tools in the server that we’ve had in the client, and we’ll explore some of the more interesting possibilities.

Chapter 17, Data and Persistence
Data. The world runs on data. This chapter first checks in with form validation, because a good data system depends on good data. Next, we look at the new data storage mechanisms now available in our browsers, including the more complex IndexedDB. And because JavaScript is now on the server, we take a peek at accessing SQL databases (accessing MongoDB is covered in Chapter 15). Lastly, we’ll explore data in the cloud, by working with Dropbox’s Datastores.
Chapter 18, JavaScript Hits the (Mobile) Road
The last chapter is about all things mobile. Well, Android and web apps mobile (sorry, no iOS coverage). Thanks to Cordova/PhoneGap, and new mobile APIs, we can now take our mad HTML5, CSS, and JavaScript skills to Android and Kindle Fire tablets and smart phones. How fun is that?
Appendix A
This appendix introduces you to jsBin and jsFiddle, which are useful for trying out the different examples in the book.

Conventions Used in This Book

The following typographical conventions are used in this book:

Indicates new terms, URLs, email addresses, filenames, and file extensions.
Constant width
Indicates computer code in a broad sense, including commands, arrays, elements, statements, options, switches, variables, attributes, keys, functions, types, classes, namespaces, methods, modules, properties, parameters, values, objects, events, event handlers, XML tags, HTML tags, macros, the contents of files, and the output from commands.
Constant width bold
Shows commands or other text that should be typed literally by the user.
Constant width italic
Shows text that should be replaced with user-supplied values or by values determined by context.


This icon signifies a tip, suggestion, or general note.


This icon indicates a warning or caution.

Websites and pages are mentioned in this book to help you locate online information that might be useful. Normally both the address (URL) and the name (title, heading) of a page are mentioned. Some addresses are relatively complicated, but you can probably locate the pages easier using your favorite search engine to find a page by its name, typically by writing it inside quotation marks. This may also help if the page cannot be found by its address; it may have moved elsewhere, but the name may still work.

Using Code Examples

Supplemental material (code examples, exercises, etc.) is available for download at https://github.com/shelleyp/javascriptcookbook.

This book is here to help you get your job done. In general, you may use the code in this book in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission.

We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: JavaScript Cookbook, Second Edition, by Shelley Powers. Copyright 2015 Shelley Powers, 978-1-491-90188-5.

If you feel your use of code examples falls outside fair use or the permission given here, feel free to contact us at .

Safari® Books Online


Safari Books Online is an on-demand digital library that delivers expert content in both book and video form from the world’s leading authors in technology and business.

Technology professionals, software developers, web designers, and business and creative professionals use Safari Books Online as their primary resource for research, problem solving, learning, and certification training.

Safari Books Online offers a range of plans and pricing for enterprise, government, education, and individuals.

Members have access to thousands of books, training videos, and prepublication manuscripts in one fully searchable database from publishers like O’Reilly Media, Prentice Hall Professional, Addison-Wesley Professional, Microsoft Press, Sams, Que, Peachpit Press, Focal Press, Cisco Press, John Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, Course Technology, and hundreds more. For more information about Safari Books Online, please visit us online.

How to Contact Us

Please address comments and questions concerning this book to the publisher:

O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)

We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at http://bit.ly/js-cookbook-2e.

To comment or ask technical questions about this book, send email to .

For more information about our books, courses, conferences, and news, see our website at http://www.oreilly.com.

Find us on Facebook: http://facebook.com/oreilly

Follow us on Twitter: http://twitter.com/oreillymedia

Watch us on YouTube: http://www.youtube.com/oreillymedia


My appreciation to my editors, Simon St. Laurent and Brian McDonald, as well as all of the rest of the O’Reilly production staff.

I also want to extend a thank you to my tech reviewers, Dr. Axel Rauschmayer and Semmy Purewal, with the caveat that any errors or gotchas still in the finished work are my responsibility.

I also want to thank the many people in the JavaScript community who generously give their time in extending the language, creating the JavaScript implementations, and the other technologies so many of us have come to depend on and appreciate. I also want to include those who write about the technologies online so the rest of us don’t have to stumble around in the dark.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required