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.

Chapter 1. Introduction

JavaScript has had a bad reputation for years. Many developers consider writing in JavaScript a pain because the programs behave so unpredictably. Once done coding, they open another browser to test, only to be greeted with an unhelpful error message (Figure 1-1). Thus, developers often simply refuse to bother studying the language.

Figure 1-1. JavaScript errors gone wild

As it turns out, most of the problems have historically been (and let’s be honest, still are) due to browser differences in the implementation of DOM and BOM, and to a much smaller extent, the JavaScript language itself.

DOM stands for Document Object Model. It’s an API (application programming interface) for working with structured documents such as those written in XML, XHTML, and HTML. DOM is a language-independent API that also exists in PHP. In JavaScript, this API is easily spotted: anything that starts with document. has to do with the DOM. As a point of historical interest, DOM started in JavaScript and was later standardized by the World Wide Web Consortium (W3C) as an API independent of JavaScript or any other language. These days, you can still unearth remnants of that primordial DOM (now called DOM0)—things like document.images (all images on a page) and document.links (all links), which were replaced in DOM version 1 with more generic methods such as document.getElementById() and document.getElementsByTagName().

BOM stands for Browser Object Model. It’s a nice name for something that’s not formally defined. It’s a collection of browser-related properties and methods, such as available screen size or the status bar. Most of these properties are available as globals such as innerWidth, although you most often see them used as properties of the window object (e.g., window.innerWidth). BOM hasn’t been standardized for a long time, so as you can imagine, there are some differences across browsers. HTML5 started to codify common behavior among browsers, including the common BOM objects.

Another term you need to know is ECMAScript. This is the core JavaScript language when you strip out the DOM and BOM. It’s the language that deals with syntax, loops, functions, objects, and so on. JavaScript started as a Netscape innovation, but was later copied by other browser vendors, raising the need for this language to establish a standard to which all implementors (browser vendors and others) would need to conform. This standard was defined by the European Computer Manufacturers Association (ECMA), now Ecma International, and called ECMAScript. These days, JavaScript should technically mean Mozilla’s implementation of ECMAScript (there’s also JScript, which is Microsoft’s implementation), but that’s not what people mean when they say “JavaScript.”

All in all, when people talk about JavaScript, they may mean an array of topics, including DOM, BOM, and ECMAScript. So:

JavaScript = ECMAScript + DOM + BOM

Scope of This Book

A good thing that has happened since the early days of the Web is that now there is a wide availability of high-quality JavaScript libraries, such as jQuery and YUI (Yahoo! User Interface Library). These libraries take the pain out of development by providing an API layer that abstracts the differences in the browser implementations of DOM and BOM—and sometimes ECMAScript itself.

The scope of this book is ECMAScript, the language itself. DOM is something you’re probably already familiar with from PHP, and BOM is not really that interesting (it’s just a collection of global variables and functions). Plus, you can always use a library to abstract the DOM and BOM. This book is independent of any particular JavaScript library, allowing you to focus on the core language and pick a library of your choice when you need one.

The book uses the term JavaScript to mean ECMAScript because using “ECMAScript” is uncommon and just plain awkward. The focus is on the most popular version of the language, ECMAScript 3 (ES3). The standards body skipped version 4 and the latest version at the time of this book’s publication is ECMAScript 5.1, which is also referred to as ES5. Although ES5 is already widely available, you cannot rely on it if you want to support older browsers, such as Internet Explorer before version 9. Chapter 6 details what’s new and different in ES5, and will help you to decide whether or not to use it. It works even in old browsers via a “shim,” or “polyfill,” as you’ll see in Shims.

The Language

Once you strip out all the DOM/BOM browser hell, what you have left is JavaScript—a beautiful, small language with a familiar C-like syntax and just a handful of built-in objects.

It’s a popular language that’s practically everywhere: on the client, server, mobile phones, desktop, and shell. Even inside PHP you can embed JavaScript using the V8Js PHP class. It’s actually harder to find an environment where you cannot run JavaScript, which means you can learn one language and use it everywhere.

It’s also an odd language when you approach it from the perspective of a PHP developer. Here are some things to be aware of early on and look for as you progress through this book:

Functions in JavaScript are objects. Arrays and regular expressions are objects, too.

Functions provide scope, and local variable scope is achieved by wrapping the code in a function.

Closures are used heavily. Although closures have existed in PHP since version 5.3, they are not yet commonly used in PHP. In JavaScript, they are everywhere.

Prototypesare an important concept in JavaScript for which there is no equivalent in PHP. It’s one of the ways JavaScript accomplishes code reuse and inheritance.

JavaScript doesn’t have a concept of classes. This is really odd from a PHP perspective and will be discussed in detail.

Learning Environment

(((“environment"To keep things simple, you don’t need to get bogged down with creating and maintaining a user interface. JavaScript doesn’t have a concept of input and output. I/O is provided by the environment that JavaScript programs run in. The most common environment is the web browser, where the responsibility for a user interface falls to HTML. You don’t need all that to study the language, so let’s just use the I/O provided by a JavaScript console.

A console lets you quickly type pieces of code and see them run, just like the interactive PHP shell you invoke on the command line:

$php-aInteractiveshellphp>echo"hi";hi

There are many JavaScript consoles to pick from and use for studying. The most accessible consoles are those provided by browsers.

Browsers

In a desktop WebKit browser (e.g., Chrome or Safari), simply load a page, right-click anywhere, and select “Inspect element” from the menu. This brings up the Web Inspector. Click the Console tab and you’re ready to go (Figure 1-2).

In newer Firefox versions, you get to a console by going to the Menu Bar and selecting Tools→Web Developer→Web Console. Alternatively, you can also install the Firebug extension, which works in any Firefox version.

Internet Explorer (since IE8) has F12 Developer Tools with a console under the Script tab.

Figure 1-2. Web Inspector console

JavaScriptCore

If you’re on a Mac, it already comes with a JavaScript interpreter capable of running shell scripts. Windows has a built-in command-line JavaScript interpreter, too, but lacks a console.

The JavaScript command-line interpreter on a Mac is a program called JavaScriptCore, which can be found in /System/Library/Frameworks/JavaScriptCore.framework/Versions/Current/Resources/jsc.

You can make an alias to it so that it’s easier to find:

Launch the Terminal application (e.g., by typing “terminal” in Spotlight).

Note that this is an even more pristine environment than the browser’s console because it has no concept of BOM and DOM, just the core JavaScript language.

Feel free to add the alias line to your ~/.profile so that it’s always there when you need it.

Note

The JavaScriptCore engine is used in WebKit-based browsers, but not in Chrome, which has its own JavaScript engine called V8.

Node.js and Rhino

If you install Node.js or Rhino on your computer, you can use their consoles, which have the benefit of working on any operating system.

Node.js is based on Google’s V8 JavaScript engine. After you install it, you can type node in the Terminal to get the console (Figure 1-4).

Figure 1-4. Node.js console

Rhino is a JavaScript interpreter by Mozilla written in Java. After you download the rhino.jar file and save it where you find appropriate (in my case, the home directory), you can bring up the console (Figure 1-5) by typing:

$java-jar~/rhino.jar

Figure 1-5. Rhino console

If you have a choice, use Node.js. You’ll notice its REPL (read-evaluate-print loop) is similar to using php -a (if not better) for exploring and experimenting with the language.

Longer Examples

Using JavaScriptCore, Node.js, or Rhino, you can create longer examples and store them in separate files. In fact, this is how you can write your own shell scripts in JavaScript. You run external files by passing them as arguments:

$jsctest.js$nodetest.js$java-jar~/rhino.jar test.js

Let’s Get Started

Armed with a handy JavaScript console, you’re ready to embark on a journey in JavaScript land. To start, Chapter 2 examines JavaScript syntax, focusing on similarities with and differences from PHP.

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