JavaScript was originally intended to be a scripting interface between a web page loaded in the browser client (Netscape Navigator at the time) and the application on the server. Since its introduction in 1995, JavaScript has become a key component of web development, and has found uses elsewhere as well.

This book covers the JavaScript language, from its most primitive data types that have been around since the beginning of the language, to its most complex features, including those that have to do with Ajax and dynamic page effects. After reading this book, you will have the basics you need to work with even the most sophisticated libraries and web applications.


Readers of this book should be familiar with web page technology, including Cascading Style Sheets (CSS) and HTML/XHTML. Previous programming experience isn’t required, though some sections may require extra review if you have no previous exposure to programming.

This book should help:

  • Anyone who wants, or needs, to integrate JavaScript into his own personal website or sites

  • Anyone who uses a content-management tool, such as a weblogging tool, and wants to better understand the scripting components incorporated into her tool templates

  • Web developers who seek to integrate JavaScript and some of the dynamic web page/Ajax features into their websites

  • Web service developers who want to develop for a new market of clients

  • Teachers who use web technologies as either the focus or a component of their courses

  • Web page designers who wish to better understand how they can enliven their designs with interactive or animated effects

  • Anyone interested in web technologies

Assumptions and Approach

As stated earlier, this book assumes you have experience with HTML and CSS, as well as a general understanding of how web applications work. Programming experience isn’t necessary, but the book covers all aspects of JavaScript, some of which are relatively sophisticated. Though the heavier pieces are few, you will need to understand JavaScript well enough to work with the newer Ajax libraries.

The Development Environment

Working with JavaScript can be especially challenging because your applications have to work not only on different types of machines, but also in several different browsers. If you look at web server logfiles for a site, you can see accesses from modern browsers, such as Firefox 3 and IE8, as well as ancient browsers such as IE5.

You can get caught up in trying to create JavaScript for all possible variations of operating system and browser, but a better bet is to pick a group of target browsers that matches the browsers used by most of the people accessing your web pages, and use these to test your applications. You may find that your applications won’t work with older browsers, but at some point, you won’t be able to support all environments for all people.

Throughout this book, I’ll be mentioning “target browsers” when I mention how a piece of JavaScript works. For the book, my target browsers are Firefox 3.x, Opera 9.x, Safari 3.x (including recent builds of WebKit, the infrastructure that forms the basis of Safari), and primarily IE8, the next version of Internet Explorer. Most of the examples for IE should also work with IE 7.x and IE 6.x, and I’ll try to note otherwise. Here is a list of the URLs where you can access these browsers:

JavaScript and browser development is very dynamic, and this adds a unique challenge when writing a book on JavaScript. Though I tried to include the most updated coverage of JavaScript, both the JavaScript specification (the ECMAScript specification, to be more accurate) and the browsers themselves were undergoing significant changes. For instance, as I was in the editing phase of this book, the ECMAScript working group announced plans to abandon work on what was known as JavaScript 2 and focus on a new interim specification release, ECMAScript 3.1. However, most of the changes in the newer ECMAScript aren’t implemented in many of the target browsers. In the cases where I was relatively confident that the specification introduced a functionality that will be implemented in future browsers, I made a note, at a minimum, of upcoming changes.

In addition, browser makers are always introducing new versions of their tools. The target browsers used to test examples in this book reflect the state of the browsers at the time I wrote the book, which may not quite reflect what you’ll find when you read the book.

However, most of the material I’ve focused on is “classic” JavaScript, which not only is stable, but also will always form the platform on which new changes to both browser and scripting language are based. Most, if not all, of the examples in this book should work in older and future browsers, as well as the target browsers used to test the examples.

Knock on wood.

How the Book Is Organized

The book is organized into six loosely grouped sections.

Chapters 1 through 3 provide an introduction to the structure of a JavaScript application, including the simple data types supported in the language, as well as the basic statements and control structures. These establish a baseline of understanding of the language for the sections that follow.

Chapters 4 and 5 introduce the main JavaScript objects, String, Number, and Boolean, in addition to other built-in objects, such as Math, RegExp (for regular expressions), Array, and the all-important Function.

Chapter 6 takes a breather from the language bits and prepares the reader for the more complex scripting examples later in the book by introducing the browser debugging tools, as well as troubleshooting techniques.

Chapter 7 introduces event handling, and Chapter 8 then expands on the subject by covering form events and JavaScript applications with forms.

Chapters 9 through 11 delve into the more sophisticated aspects of web page development. These chapters cover the Browser Object Model (BOM) and the newer Document Object Model (DOM), and show how you can create your own custom objects. Understanding these models is essential if you wish to create new windows, or individually access, modify, or even dynamically create any page element. In addition, with custom objects, you can move beyond the capabilities that are pre-built into either language or browser. Also included in these chapters is a look at browser cookies and some of the more modern client-side storage techniques.

Chapters 12 through 15 finish the book by diving into the advanced uses of JavaScript, including dynamic page effects and Ajax, as well as a more detailed look at using XML or JavaScript Object Notation (JSON) with Ajax applications.

Though I try to follow a logical course when covering JavaScript, sometimes I’ll need to use functionality in an example that I won’t cover in detail until a later chapter. When this occurs, I’ll try to make a note about which chapter includes coverage of the more advanced functionality.

A Chapter Breakdown

The following is a detailed breakdown of this book’s contents, including a brief description of what each chapter covers:

Chapter 1, Hello JavaScript!

Introduces JavaScript and provides a quick first look at a small web page application. This chapter also covers some issues associated with the use of JavaScript, including some good programming practices recommended for JavaScript applications.

Chapter 2, JavaScript Data Types and Variables

Provides an overview of the basic data types in JavaScript, as well as an overview of language variables, identifiers, and the structure of a JavaScript statement.

Chapter 3, Operators and Statements

Covers the basic statements of JavaScript, including assignment, conditional, and control statements, as well as the operators necessary for all three.

Chapter 4, The JavaScript Objects

Introduces the three primary built-in JavaScript objects, including Number, String, and Boolean, as well as Date and Math. The chapter also introduces the RegExp object, which provides the facilities to do pattern matching.

Chapter 5, Functions

Focuses on one other JavaScript built-in object: Function. Function is key to creating custom objects, as well as packaging blocks of JavaScript into reusable functionality that can be invoked more than once in an application.

Chapter 6, Troubleshooting, Debugging, and Cross-Browser Issues

Briefly introduces the debugging environments for the book’s target browsers (Internet Explorer, Safari, Firefox, and Opera), as well as covers basic cross-browser development.

Chapter 7, Catching Events

Focuses on event handling, including both the original form of event handling (which is still commonly used in many applications) as well as the newer DOM-based event handling.

Chapter 8, Forms, Form Events, and Validation

Introduces using JavaScript with forms and form fields, including how to access each field type—such as text input fields and drop-down lists—and validate the data once retrieved. Form validation before the form is submitted to the web server helps prevent an unnecessary round trip to the server, and thus saves both time and resource use. This chapter also briefly introduces issues related to security and forms.

Chapter 9, Browser As Puzzle Box

Begins to look at object models accessible from JavaScript, starting with the Browser Object Model—a hierarchy of objects including the window, document, forms, history, location, and so on. Through the BOM, JavaScript can open windows; access page elements such as forms, links, and images; and even create some basic dynamic effects.

Chapter 10, Cookies and Other Client-Side Storage Techniques

Covers script-based cookies, which store small pieces of data on the client’s machine. With cookies, you can store usernames, passwords, and other information so that users don’t have to keep reentering data. In addition, this chapter provides a brief overview of new and upcoming client-side storage techniques, such as Google’s Gears and HTML5 local storage that offer capabilities beyond what a cookie can provide. The chapter also includes a review of the JavaScript sandbox.

Chapter 11, The DOM, or Web Page As Tree

Focuses on the DOM, a straightforward, but not trivial, object model that provides access to all document elements and attributes. Though the model is comprehensive and its coverage is fairly straightforward, the chapter could present some challenging moments for new programmers.

Chapter 12, Dynamic Pages

Provides a general introduction to dynamically altering the web page, including modifying an individual element’s style, as well as adding and removing elements from the page. Some of the effects we’ll explore in this chapter include drag-and-drop, collapsing and expanding page sections, visibility, and movement. An understanding of CSS is required.

Chapter 13, Creating Custom JavaScript Objects

Demonstrates how to create custom objects in JavaScript and covers the prototype structure that enables such structures in the language. We’ll discuss some programming language concepts, such as inheritance and encapsulation, but you don’t need prior experience with these concepts to benefit from reading this chapter.

Chapter 14, Moving Outside the Page with Ajax

Introduces Ajax, which, despite all the excitement it has generated, is actually not a complicated use of JavaScript. The chapter walks through a complete example, including server-side code.

Chapter 15, Ajax Data: XML or JSON?

Expands on the example in Chapter 14 that demonstrated Ajax with an HTML fragment by demonstrating how to generate and process XML through an Ajax application, and then how to do the same with JSON. We’ll cover the advantages of both techniques, as well as when to use one over the other.

Conventions Used in This Book

The following typographical conventions are used in this book:

Constant width

Used for command lines and options that should be typed verbatim, C# keywords, and code examples

Constant width italic

Used for replaceable items, such as variables or optional elements, within syntax lines or code

Constant width bold

Used for emphasis within program code


Used for pathnames, filenames, Internet addresses (such as domain names and URLs), and new terms where they are defined


Indicates a tip, suggestion, or general note.


Indicates a warning or caution.

Using Code Examples

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: “Learning JavaScript, Second Edition, by Shelley Powers. Copyright 2009 Shelley Powers, 978-0-596-52187-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


When you see a Safari® Books Online icon on the cover of your favorite technology book, that means the book is available online through the O’Reilly Network Safari Bookshelf.

Safari offers a solution that’s better than e-books. It’s a virtual library that lets you easily search thousands of top tech books, cut and paste code samples, download chapters, and find quick answers when you need the most accurate, current information. Try it for free at

How to Contact Us

We have tested and verified the information in this book to the best of our ability, but you might find that features have changed (or even that we have made mistakes!). Please let us know about any errors you find, as well as your suggestions for future editions, by writing to:

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

To ask technical questions or comment on the book, send email to:

We have a web page for this book where we list examples and any plans for future editions. You can access this information at:

For more information about books, conferences, Resource Centers, and the O’Reilly Network, see the O’Reilly website at:


I want to thank my editing and review team for helping me write a better book. This includes technical editors Tony Ruscoe, Jeni Tennison, Matthew Russell, and Trey Holdener, who did an excellent job reviewing the content, as well as my long-time editor, Simon St.Laurent. In addition, I’d like to thank the other members of the production team: Rachel Monaghan, Sumita Mukherji, Joe Wizda, and Jessamyn Read.

Get Learning JavaScript, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.