100% found this document useful (1 vote)
32 views

[Ebooks PDF] download JavaScript The Definitive Guide Fourth Edition Flanagan full chapters

The document provides information about the fourth edition of 'JavaScript: The Definitive Guide' by David Flanagan, detailing updates and changes made since the previous edition. It emphasizes the evolution of JavaScript, its standards, and the importance of focusing on specifications for better portability and maintainability of code. Additionally, it addresses common myths about JavaScript, clarifying its relationship with Java and its complexity as a programming language.

Uploaded by

naicaravlic15
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
32 views

[Ebooks PDF] download JavaScript The Definitive Guide Fourth Edition Flanagan full chapters

The document provides information about the fourth edition of 'JavaScript: The Definitive Guide' by David Flanagan, detailing updates and changes made since the previous edition. It emphasizes the evolution of JavaScript, its standards, and the importance of focusing on specifications for better portability and maintainability of code. Additionally, it addresses common myths about JavaScript, clarifying its relationship with Java and its complexity as a programming language.

Uploaded by

naicaravlic15
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

Visit https://ebookfinal.

com to download the full version and


explore more ebooks

JavaScript The Definitive Guide Fourth Edition


Flanagan

_____ Click the link below to download _____


https://ebookfinal.com/download/javascript-the-
definitive-guide-fourth-edition-flanagan/

Explore and download more ebooks at ebookfinal.com


Here are some suggested products you might be interested in.
Click the link to download

JavaScript the Definitive Guide Activate Your Web Pages


6th ed Edition Flanagan

https://ebookfinal.com/download/javascript-the-definitive-guide-
activate-your-web-pages-6th-ed-edition-flanagan/

JavaScript Pocket Reference Third Edition David Flanagan

https://ebookfinal.com/download/javascript-pocket-reference-third-
edition-david-flanagan/

Cassandra The Definitive Guide 3rd Edition Jeff Carpenter

https://ebookfinal.com/download/cassandra-the-definitive-guide-3rd-
edition-jeff-carpenter/

Elasticsearch The Definitive Guide 1st Edition Clinton


Gormley

https://ebookfinal.com/download/elasticsearch-the-definitive-
guide-1st-edition-clinton-gormley/
Automotive Ethernet the Definitive Guide 1.2 Edition Bob
Metcalfe

https://ebookfinal.com/download/automotive-ethernet-the-definitive-
guide-1-2-edition-bob-metcalfe/

The Definitive Guide to HTML5 1st Edition Adam Freeman

https://ebookfinal.com/download/the-definitive-guide-to-html5-1st-
edition-adam-freeman/

HTML XHTML The Definitive Guide Sixth Edition Chuck


Musciano

https://ebookfinal.com/download/html-xhtml-the-definitive-guide-sixth-
edition-chuck-musciano/

Ethernet The Definitive Guide 2nd Edition Charles E.


Spurgeon

https://ebookfinal.com/download/ethernet-the-definitive-guide-2nd-
edition-charles-e-spurgeon/

Hadoop The Definitive Guide 4th ed Edition Tom White

https://ebookfinal.com/download/hadoop-the-definitive-guide-4th-ed-
edition-tom-white/
JavaScript The Definitive Guide Fourth Edition Flanagan
Digital Instant Download
Author(s): Flanagan, David
ISBN(s): 9780596000486, 0596000480
Edition: Fourth
File Details: PDF, 2.66 MB
Year: 2001
Language: english
JavaScript: The
Definitive Guide, 4th
Edition
By David Flanagan

E-Book Ripped by lilmeanman Enjoy! http://www.magic-html.com -- Free Apps, E-Books, ETC


Digitally signed by Lilmeanman

Lilmeanman DN: CN = Lilmeanman, C = US, O = Lilmeanman UNltd, OU = Lilmeanman UNltd


Reason: I attest to the accuracy and integrity of this document
Date: 2004.08.31 17:19:43 -06'00'
Dedication
This book is dedicated to all who teach peace and
resist violence.
Preface
There have been many changes in the world of web programming with JavaScript
since the third edition of this book was published, including:

• Second and third editions of the ECMA-262 standard have been published,
updating the core JavaScript language. Conformant versions of Netscape's
JavaScript interpreter and Microsoft's JScript interpreter have been released.
• The source code for Netscape's JavaScript interpreters (one written in C and one
written in Java ) has been released as open source and is available to anyone
who wants to embed a scripting language in his application.
• The World Wide Web Consortium (W3C) has published two versions (or levels)
of a Document Object Model (DOM) standard. Recent browsers support this
standard (to varying degrees) and allow client-side JavaScript to interact with
document content to produce sophisticated Dynamic HTML (DHTML) effects.
Support for other W3C standards, such as HTML 4, CSS1, and CSS2, has also
become widespread.
• The Mozilla organization, using source code originally contributed by Netscape,
has produced a good fifth-generation browser. At the time of this writing, the
Mozilla browser is not yet at the 1.0 release level, but the browser is mature
enough that Netscape has based its 6.0 and 6.1 browsers upon the Mozilla code
base.
• Microsoft's Internet Explorer has become the overwhelmingly dominant browser
on desktop systems. However, the Netscape/Mozilla browser remains relevant to
web developers, especially because of its superior support for web standards. In
addition, minor browsers such as Opera (http://www.opera.com) and Konquerer
(http://www.konqueror.org) should be seen as equally relevant.
• Web browsers (and JavaScript interpreters) are no longer confined to the desktop
but have migrated to PDAs and even cell phones.

In summary, the core JavaScript language has matured. It has been standardized and is
used in a wider variety of environments than it was previously. The collapse of
Netscape's market share has allowed the universe of desktop web browsers to expand,
and JavaScript-enabled web browsers have also become available on non-desktop
platforms. There has been a distinct, if not complete, move toward web standards. The
(partial) implementation of the DOM standard in recent browsers gives web developers a
long-awaited vendor-independent API to which they can code.
What's New in the Fourth Edition
This edition of JavaScript: The Definitive Guide has been thoroughly updated in light of
the changes I just described. Major new features include complete coverage of JavaScript
1.5 and the third edition of the ECMA-262 standard on which it is based, and complete
coverage of the Level 2 DOM standard.

Throughout the book, the focus has shifted from documenting particular JavaScript and
browser implementations ( JavaScript 1.2, Netscape 4, Internet Explorer 5, etc.) to
documenting the standards upon which those implementations are (or ought to be) based.
Because of the proliferation of implementations, it is no longer practical for any one book
to attempt to document -- or for any one developer to attempt to understand -- every
feature, proprietary extension, quirk, and bug of every implementation. Focusing on the
specifications instead of the implementations makes this book easier to use and, if you
take the same approach, will make your JavaScript code more portable and maintainable.
You'll particularly notice the increased emphasis on standards in the new material on core
JavaScript and the DOM.

Another major change in this edition is that the reference section has been split into three
distinct parts. First, the core JavaScript material has been separated from the client-side
JavaScript material (Part IV) and placed in a section of its own (Part III). This division is
for the convenience of JavaScript programmers who are working with the language in an
environment other than a web browser and who are not interested in client-side
JavaScript.

Second, the new material documenting the W3C DOM has been placed in a section of its
own (Part V), separate from the existing client-side JavaScript material. The DOM
standard defines an API that is quite distinct from the "legacy" API of traditional client-
side JavaScript. Depending on the browser platforms they are targeting, developers
typically use one API or the other and usually do not need to switch back and forth.
Keeping these two APIs distinct also preserves the organization of the existing client-side
reference material, which is convenient for readers of the third edition who upgrade to
this edition.

In order to accommodate all the new material without making the book much, much
larger, I've gotten rid of reference pages for the trivial properties of objects. These
properties are already described once on the reference page for the object, and putting
another description in a reference page of its own was redundant and wasteful. Properties
that require substantial description, as well as all methods, still have reference pages of
their own. Furthermore, the design wizards at O'Reilly have created a new interior design
for the book that remains easy and pleasant to read but takes up less space.

Conventions Used in This Book


I use the following formatting conventions in this book:
Bold

Is occasionally used to refer to particular keys on a computer keyboard or to


portions of a user interface, such as the Back button or the Options menu.

Italic

Is used for emphasis and to signify the first use of a term. Italic is also used for
email addresses, web sites, FTP sites, file and directory names, and newsgroups.
Finally, italic is used in this book for the names of Java classes, to help keep Java
class names distinct from JavaScript names.

Constant width

Is used in all JavaScript code and HTML text listings, and generally for anything
that you would type literally when programming.

Constant width italic

Is used for the names of function arguments, and generally as a placeholder to


indicate an item that should be replaced with an actual value in your program.

Finding the Examples Online


The examples printed in this book are available for download from the book's web site.
Follow the Examples link from the book's catalog page:

http://www.oreilly.com/catalog/jscript4/

Acknowledgments
Brendan Eich of the Mozilla organization is the originator and chief innovator of
JavaScript. I, and many JavaScript developers, owe Brendan a tremendous debt of
gratitude for developing JavaScript and for taking the time out of his crazy schedule to
answer our questions and even solicit our input. Besides patiently answering my many
questions, Brendan also read and provided very helpful comments on the first and third
editions of this book.

This book has been blessed with top-notch technical reviewers, whose comments have
gone a long way toward making it a stronger, more accurate book. Waldemar Horwat at
Netscape reviewed the new material on JavaScript 1.5 in this fourth edition. The new
material on the W3C DOM was reviewed by Philippe Le Hegaret of the W3C; by Peter-
Paul Koch, Head of Client-Side Programming at the Dutch Internet consultancy and
creation company Netlinq Framfab (http://www.netlinqframfab.nl); by Dylan Schiemann
of SitePen (http://www.sitepen.com); and by independent web developer Jeff Yates. Two
of these reviewers maintain useful web sites about web design with the DOM. Peter-
Paul's site is at http://www.xs4all.nl/~ppk/js/. Jeff's site is http://www.pbwizard.com.
Although he was not a reviewer, Joseph Kesselman of IBM Research was very helpful in
answering my questions about the W3C DOM.

The third edition of the book was reviewed by Brendan Eich, Waldemar Horwat, and
Vidur Apparao at Netscape; Herman Venter at Microsoft; and two independent
JavaScript developers, Jay Hodges and Angelo Sirigos. Dan Shafer of CNET's
Builder.Com did some preliminary work on the third edition. Although his material was
not used in this edition, his ideas and general outline were quite helpful. Norris Boyd and
Scott Furman at Netscape also provided useful information for this edition, and Vidur
Apparao of Netscape and Scott Issacs of Microsoft each took the time to talk to me about
the forthcoming Document Object Model standard. Finally, Dr. Tankred Hirschmann
provided challenging insights into the intricacies of JavaScript 1.2.

The second edition benefited greatly from the help and comments of Nick Thompson and
Richard Yaker of Netscape; Dr. Shon Katzenberger, Larry Sullivan, and Dave C.
Mitchell at Microsoft; and Lynn Rollins of R&B Communications. The first edition was
reviewed by Neil Berkman of Bay Networks, and by Andrew Schulman and Terry Allen
of O'Reilly & Associates.

This book also gains strength from the diversity of editors it has had. Paula Ferguson is
the editor of this edition and of the third edition. She's given the book a thorough and
much-needed going over, making it easier to read and easier to understand. Frank
Willison edited the second edition, and Andrew Schulman edited the first.

Finally, my thanks, as always and for so many reasons, to Christie.

—David Flanagan, September 2001


Chapter 1. Introduction to JavaScript
JavaScript is a lightweight, interpreted programming language with object-oriented
capabilities. The general-purpose core of the language has been embedded in Netscape,
Internet Explorer, and other web browsers and embellished for web programming with
the addition of objects that represent the web browser window and its contents. This
client-side version of JavaScript allows executable content to be included in web pages --
it means that a web page need no longer be static HTML, but can include programs that
interact with the user, control the browser, and dynamically create HTML content.

Syntactically, the core JavaScript language resembles C, C++, and Java, with
programming constructs such as the if statement, the while loop, and the && operator.
The similarity ends with this syntactic resemblance, however. JavaScript is an untyped
language, which means that variables do not need to have a type specified. Objects in
JavaScript are more like Perl's associative arrays than they are like structures in C or
objects in C++ or Java. The object-oriented inheritance mechanism of JavaScript is like
those of the little-known languages Self and NewtonScript; it is quite different from
inheritance in C++ and Java. Like Perl, JavaScript is an interpreted language, and it
draws inspiration from Perl in a number of places, such as its regular expression and
array-handling features.

This chapter provides a quick overview of JavaScript; it explains what JavaScript can and
cannot do and exposes some myths about the language. It distinguishes the core
JavaScript language from embedded and extended versions of the language, such as the
client-side JavaScript that is embedded in web browsers and the server-side JavaScript
that is embedded in Netscape's web servers. (This book documents core and client-side
JavaScript.) This chapter also demonstrates real-world web programming with some
client-side JavaScript examples.

1.1 JavaScript Myths


JavaScript is the subject of a fair bit of misinformation and confusion. Before proceeding
any further with our exploration of JavaScript, it is important that we debunk some
common and persistent myths about the language.

1.1.1 JavaScript Is Not Java

One of the most common misconceptions about JavaScript is that it is a simplified


version of Java, the programming language from Sun Microsystems. Other than an
incomplete syntactic resemblance and the fact that both Java and JavaScript can provide
executable content in web browsers, the two languages are entirely unrelated. The
similarity of names is purely a marketing ploy (the language was originally called
LiveScript; its name was changed to JavaScript at the last minute).
JavaScript and Java do, however, make a good team. The two languages have different
sets of capabilities. JavaScript can control browser behavior and content but cannot draw
graphics or perform networking. Java has no control over the browser as a whole but can
do graphics, networking, and multithreading. Client-side JavaScript can interact with and
control Java applets embedded in a web page, and, in this sense, JavaScript really can
script Java (see Chapter 22 for details).

1.1.2 JavaScript Is Not Simple

JavaScript is touted as a scripting language instead of a programming language, the


implication being that scripting languages are simpler, that they are programming
languages for non-programmers. Indeed, JavaScript appears at first glance to be a fairly
simple language, perhaps of the same complexity as BASIC. JavaScript does have a
number of features designed to make it more forgiving and easier to use for new and
unsophisticated programmers. Non-programmers can use JavaScript for limited,
cookbook-style programming tasks.

Beneath its thin veneer of simplicity, however, JavaScript is a full-featured programming


language, as complex as any and more complex than some. Programmers who attempt to
use JavaScript for nontrivial tasks often find the process frustrating if they do not have a
solid understanding of the language. This book documents JavaScript comprehensively,
so you can develop a sophisticated understanding of the language.

1.2 Versions of JavaScript


JavaScript has evolved over the years, and Netscape has released several versions of the
language. Microsoft has released similar versions of the JavaScript language under the
name "JScript." And ECMA (http://www.ecma.ch) has published three versions of the
ECMA-262 standard that standardize the JavaScript language under the awkward name
"ECMAScript."

Table 1-1 lists these various versions and explains their key features and how they are
related to one another. In this book, I often use the name "JavaScript" to refer to any
implementation of the language, including Microsoft's JScript. When I'm specifically
referring to ECMAScript, I often use the terms "ECMA-262" or "ECMA."

Table 1-1. Versions of JavaScript


Version Description
JavaScript The original version of the language. It was buggy and is now essentially
1.0 obsolete. Implemented by Netscape 2.
JavaScript Introduced a true Array object; most serious bugs resolved. Implemented by
1.1 Netscape 3.
Table 1-1. Versions of JavaScript
Version Description
Introduced the switch statement, regular expressions, and a number of other
JavaScript
features. Almost compliant with ECMA v1, but has some incompatibilities.
1.2
Implemented by Netscape 4.
JavaScript Fixed incompatibilities of JavaScript 1.2. Compliant with ECMA v1.
1.3 Implemented by Netscape 4.5.
JavaScript
Implemented only in Netscape server products.
1.4
JavaScript Introduced exception handling. Compliant with ECMA v3. Implemented by
1.5 Mozilla and Netscape 6.
Roughly equivalent to JavaScript 1.0. Implemented by early releases of IE
JScript 1.0
3.
JScript 2.0 Roughly equivalent to JavaScript 1.1. Implemented by later releases of IE 3.
Roughly equivalent to JavaScript 1.3. Compliant with ECMA v1.
JScript 3.0
Implemented by IE 4.
JScript 4.0 Not implemented by any web browser.
Supported exception handling. Partially compliant with ECMA v3.
JScript 5.0
Implemented by IE 5.
Roughly equivalent to JavaScript 1.5. Fully compliant with ECMA v3.
Implemented by IE 5.5 and IE 6. (IE 6 actually implements JScript 5.6, but
JScript 5.5
5.6 is not different from 5.5 in any way that is relevant to client-side
JavaScript programmers.)
The first standard version of the language. Standardized the basic features of
JavaScript 1.1 and added a few new features. Did not standardize the
ECMA v1
switch statement or regular expression support. Conformant
implementations are JavaScript 1.3 and JScript 3.0.
A maintenance release of the standard that included clarifications but
ECMA v2
defined no new features.
Standardized the switch statement, regular expressions, and exception
ECMA v3
handling. Conformant implementations are JavaScript 1.5 and JScript 5.5.

1.3 Client-Side JavaScript


When a JavaScript interpreter is embedded in a web browser, the result is client-side
JavaScript. This is by far the most common variant of JavaScript; when most people refer
to JavaScript, they usually mean client-side JavaScript. This book documents client-side
JavaScript, along with the core JavaScript language that client-side JavaScript
incorporates.

We'll discuss client-side JavaScript and its capabilities in much more detail later in this
chapter. In brief, though, client-side JavaScript combines the scripting ability of a
JavaScript interpreter with the document object model (DOM) defined by a web browser.
These two distinct technologies combine in a synergistic way, so the result is greater than
the sum of its parts: client-side JavaScript enables executable content to be distributed
over the Web and is at the heart of a new generation of Dynamic HTML (DHTML)
documents.

Just as the ECMA-262 specification defined a standard version of the core JavaScript
language, the World Wide Web Consortium (W3C) has published a DOM specification
(or recommendation) that standardizes the features a browser must support in its DOM.
We'll learn much more about this standard in Chapter 17, Chapter 18, and Chapter 19.
Although the W3C DOM standard is not yet as well supported as it could be, it is
supported well enough that web developers can start writing JavaScript code that relies
on it.

Table 1-2 shows the core language version and DOM capabilities supported by various
browser versions from Netscape and Microsoft. Note that the versions of Internet
Explorer listed in the table refer to the Windows version of that browser. The capabilities
of Macintosh versions of IE often vary (sometimes significantly) from the same-
numbered versions for Windows. Also, bear in mind that IE allows the JScript interpreter
to be upgraded independently of the browser itself, so it is possible to encounter an
installation of IE that supports a version of the language greater than that shown here.

Table 1-2. Client-side JavaScript features by browser


Browser Language DOM capabilities
JavaScript
Netscape 2 Form manipulation
1.0
JavaScript
Netscape 3 Image rollovers
1.1
JavaScript
Netscape 4 DHTML with Layers
1.2
JavaScript
Netscape 4.5 DHTML with Layers
1.3
Netscape 6 / JavaScript Substantial support for W3C DOM standard; support for
Mozilla 1.5 Layers discontinued
IE 3 JScript Form manipulation
Table 1-2. Client-side JavaScript features by browser
Browser Language DOM capabilities
1.0/2.0
IE 4 JScript 3.0 Image rollovers; DHTML with document.all[]
IE 5 JScript 5.0 DHTML with document.all[]
IE 5.5 JScript 5.5 Partial support for W3C DOM standard
Partial support for W3C DOM standard; lacks support
IE 6 JScript 5.5
for W3C DOM event model

The differences and incompatibilities between Netscape's and Microsoft's client-side


versions of JavaScript are much greater than the differences between their respective
implementations of the core language. However, both browsers do agree upon a large
subset of client-side JavaScript features. For lack of better names, versions of client-side
JavaScript are sometimes referred to by the version of the core language on which they
are based. Thus, in client-side contexts the term "JavaScript 1.2" refers to the version of
client-side JavaScript supported by Netscape 4 and Internet Explorer 4. When I use core-
language version numbers to refer to client-side versions of JavaScript, I am referring to
the compatible subset of features supported by both Netscape and Internet Explorer.
When I discuss client-side features specific to one browser or the other, I refer to the
browser by name and version number.

Note that Netscape and Internet Explorer are not the only browsers that support client-
side JavaScript. For example, Opera (http://www.opera.com) supports client-side
JavaScript as well. However, since Netscape and Internet Explorer have the vast majority
of market share, they are the only browsers discussed explicitly in this book. Client-side
JavaScript implementations in other browsers should conform fairly closely to the
implementations in these two browsers.

Similarly, JavaScript is not the only programming language that can be embedded within
a web browser. For example, Internet Explorer supports a language known as VBScript, a
variant of Microsoft's Visual Basic language that provides many of the same features as
JavaScript but can be used only with Microsoft browsers. Also, the HTML 4.0
specification uses the Tcl programming language as an example of an embedded scripting
language in its discussion of the HTML <script> tag. While there are no mainstream
browsers that support Tcl for this purpose, there is no reason that a browser could not
easily support this language.

Previous editions of this book have covered Netscape browsers more thoroughly than
Microsoft browsers. The reason for this bias was that Netscape was the inventor of
JavaScript and (for a time, at least) held the dominant position in the web-browser
market. This bias toward Netscape has declined in each subsequent edition of the book,
and the current edition is heavily focused on standards, such as ECMAScript and the
W3C DOM, rather than on particular browsers. Nevertheless, readers may find that some
of the original bias toward Netscape comes through in the material that remains from
older editions.

1.4 JavaScript in Other Contexts


JavaScript is a general-purpose programming language; its use is not restricted to web
browsers. JavaScript was designed to be embedded within, and provide scripting
capabilities for, any application. From the earliest days, in fact, Netscape's web servers
included a JavaScript interpreter, so that server-side scripts could be written in
JavaScript. Similarly, Microsoft uses its JScript interpreter in its IIS web server and in its
Windows Scripting Host product, in addition to using it in Internet Explorer.

Both Netscape and Microsoft have made their JavaScript interpreters available to
companies and programmers who want to embed them in their applications. Netscape's
interpreter was released as open source and is now available through the Mozilla
organization (see http://www.mozilla.org/js/). Mozilla actually provides two different
versions of the JavaScript 1.5 interpreter. One is written in C and is called
"SpiderMonkey." The other is written in Java and, in a flattering reference to this book, is
called "Rhino."

We can expect to see more and more applications that use JavaScript as an embedded
scripting language.[1] If you are writing scripts for such an application, you'll find the first
half of this book, documenting the core language, to be useful. The web-browser specific
chapters, however, will probably not be applicable to your scripts.
[1]
ActionScript, the scripting language available in Macromedia's Flash 5, is modeled after the ECMAScript standard, but it is not actually
JavaScript.

1.5 Client-Side JavaScript: Executable Content in


Web Pages
When a web browser is augmented with a JavaScript interpreter, it allows executable
content to be distributed over the Internet in the form of JavaScript scripts. Example 1-1
shows a simple JavaScript program, or script, embedded in a web page.

Example 1-1. A simple JavaScript program


<html>
<body>
<head><title>Factorials</title></head>
<script language="JavaScript">
document.write("<h2>Table of Factorials</h2>");
for(i = 1, fact = 1; i < 10; i++, fact *= i) {
document.write(i + "! = " + fact);
document.write("<br>");
}
</script>
</body>
</html>

When loaded into a JavaScript-enabled browser, this script produces the output shown in
Figure 1-1.

Figure 1-1. A web page generated with JavaScript

As you can see in this example, the <script> and </script> tags are used to embed
JavaScript code within an HTML file. We'll learn more about the <script> tag in
Chapter 12. The main feature of JavaScript demonstrated by this example is the use of the
document.write( ) method.[2] This method is used to dynamically output HTML text
that is parsed and displayed by the web browser; we'll encounter it many more times in
this book.
[2]
"Method" is the object-oriented term for function or procedure; you'll see it used throughout this book.

Besides allowing control over the content of web pages, JavaScript allows control over
the browser and over the content of the HTML forms that appear in the browser. We'll
learn about these capabilities of JavaScript in more detail later in this chapter and in
much more detail later in this book.

JavaScript can control not only the content of HTML documents, but also the behavior of
those documents. That is, a JavaScript program might respond in some way when you
enter a value in an input field or click on an image in a document. JavaScript does this by
defining event handlers for the document -- pieces of JavaScript code that are executed
when a particular event occurs, such as when the user clicks on a button. Example 1-2
shows the definition of a simple HTML form that includes an event handler that is
executed in response to a button click.
Example 1-2. An HTML form with a JavaScript event handler defined
<form>
<input type="button"
value="Click here"
onclick="alert('You clicked the button');">
</form>

Figure 1-2 illustrates the result of clicking the button.

Figure 1-2. The JavaScript response to an event

The onclick attribute shown in Example 1-2 was originally a Netscape extension added
to HTML specifically for client-side JavaScript. Now, however, this and other event
handler attributes have been standardized in HTML Version 4.0. All JavaScript event
handlers are defined with HTML attributes like this one. The value of the onclick
attribute is a string of JavaScript code to be executed when the user clicks the button. In
this case, the onclick event handler calls the alert( ) function. As you can see in
Figure 1-2, alert( ) pops up a dialog box to display the specified message.

Example 1-1 and Example 1-2 highlight only the simplest features of client-side
JavaScript. The real power of JavaScript on the client side is that scripts have access to a
hierarchy of objects that are based on the content of the web page. For example, client-
side JavaScript programs can access and manipulate each of the images that appear in a
document and can communicate and interact with Java applets and other objects
embedded within an HTML document. Once you have mastered the core JavaScript
language, the key to using JavaScript effectively in web pages is learning to use the
features of the DOM exposed by the browser.

1.6 Client-Side JavaScript Features


Another possible use of JavaScript is for writing programs to perform arbitrary
computations. You can write simple scripts, for example, that compute Fibonacci
numbers, or search for primes. In the context of the Web and web browsers, however, a
more interesting application of the language might be a program that computed the sales
tax on an online order, based on information supplied by the user in an HTML form. As
mentioned earlier, the real power of JavaScript lies in the browser and document-based
objects that the language supports. To give you an idea of JavaScript's potential, the
following sections list and explain the important capabilities of client-side JavaScript and
the objects it supports.

1.6.1 Control Document Appearance and Content

The JavaScript Document object, through its write( ) method, which we have already
seen, allows you to write arbitrary HTML into a document as the document is being
parsed by the browser. For example, you can include the current date and time in a
document or display different content on different platforms.

You can also use the Document object to generate documents entirely from scratch.
Properties of the Document object allow you to specify colors for the document
background, the text, and the hypertext links within it. This amounts to the ability to
generate dynamic and conditional HTML documents, a technique that works particularly
well in multiframe documents. Indeed, in some cases dynamic generation of frame
content allows a JavaScript program to replace a traditional server-side script entirely.

Internet Explorer 4 and Netscape 4 support proprietary techniques for producing


Dynamic HTML effects that allow document content to be dynamically generated,
moved, and altered. IE 4 also supports a complete DOM that gives JavaScript access to
every single HTML element within a document. And IE 5.5 and Netscape 6 support the
W3C DOM standard (or at least key portions of it), which defines a standard, portable
way to access all of the elements and text within an HTML document and to position
them and modify their appearance by manipulating their Cascading Style Sheets (CSS)
style attributes. In these browsers, client-side JavaScript has complete power over
document content, which opens an unlimited world of scripting possibilities.

1.6.2 Control the Browser

Several JavaScript objects allow control over the behavior of the browser. The Window
object supports methods to pop up dialog boxes to display simple messages to the user
and get simple input from the user. This object also defines a method to create and open
(and close) entirely new browser windows, which can have any specified size and any
combination of user controls. This allows you, for example, to open up multiple windows
to give the user multiple views of your web site. New browser windows are also useful
for temporary display of generated HTML, and, when created without the menu bar and
other user controls, these windows can serve as dialog boxes for more complex messages
or user input.

JavaScript does not define methods that allow you to create and manipulate frames
directly within a browser window. However, the ability to generate HTML dynamically
allows you to programmatically write the HTML tags that create any desired frame
layout.
JavaScript also allows control over which web pages are displayed in the browser. The
Location object allows you to download and display the contents of any URL in any
window or frame of the browser. The History object allows you to move forward and
back within the user's browsing history, simulating the action of the browser's Forward
and Back buttons.

Yet another method of the Window object allows JavaScript to display arbitrary
messages to the user in the status line of any browser window.

1.6.3 Interact with HTML Forms

Another important aspect of client-side JavaScript is its ability to interact with HTML
forms. This capability is provided by the Form object and the form element objects it can
contain: Button, Checkbox, Hidden, Password, Radio, Reset, Select, Submit, Text, and
Textarea objects. These element objects allow you to read and write the values of the
input elements in the forms in a document. For example, an online catalog might use an
HTML form to allow the user to enter his order and could use JavaScript to read the input
from that form in order to compute the cost of the order, the sales tax, and the shipping
charge. JavaScript programs like this are, in fact, very common on the Web. We'll see a
program shortly that uses an HTML form and JavaScript to allow the user to compute
monthly payments on a home mortgage or other loan. JavaScript has an obvious
advantage over server-based scripts for applications like these: JavaScript code is
executed on the client, so the form's contents don't have to be sent to the server in order
for relatively simple computations to be performed.

Another common use of client-side JavaScript with forms is for validating form data
before it is submitted. If client-side JavaScript is able to perform all necessary error
checking of a user's input, no round trip to the server is required to detect and inform the
user of trivial input errors. Client-side JavaScript can also perform preprocessing of input
data, which can reduce the amount of data that must be transmitted to the server. In some
cases, client-side JavaScript can eliminate the need for scripts on the server altogether!
(On the other hand, JavaScript and server-side scripting do work well together. For
example, a server-side program can dynamically create JavaScript code on the fly, just as
it dynamically creates HTML.)

1.6.4 Interact with the User

An important feature of JavaScript is the ability to define event handlers -- arbitrary


pieces of code to be executed when a particular event occurs. Usually, these events are
initiated by the user, when, for example, she moves the mouse over a hypertext link,
enters a value in a form, or clicks the Submit button in a form. This event-handling
capability is a crucial one, because programming with graphical interfaces, such as
HTML forms, inherently requires an event-driven model. JavaScript can trigger any kind
of action in response to user events. Typical examples might be to display a special
message in the status line when the user positions the mouse over a hypertext link or to
pop up a confirmation dialog box when the user submits an important form.
1.6.5 Read and Write Client State with Cookies

A cookie is a small amount of state data stored permanently or temporarily by the client.
Cookies may be transmitted along with a web page by the server to the client, which
stores them locally. When the client later requests the same or a related web page, it
passes the relevant cookies back to the server, which can use their values to alter the
content it sends back to the client. Cookies allow a web page or web site to remember
things about the client -- for example, that the user has previously visited the site, has
already registered and obtained a password, or has expressed a preference about the color
and layout of web pages. Cookies help you provide the state information that is missing
from the stateless HTTP protocol of the Web.

When cookies were invented, they were intended for use exclusively by server-side
scripts; although stored on the client, they could be read or written only by the server.
JavaScript changed this, because JavaScript programs can read and write cookie values
and can dynamically generate document content based on the value of cookies.

1.6.6 Still More Features

In addition to the features I have already discussed, JavaScript has many other
capabilities, including the following:

• JavaScript can change the image displayed by an <img> tag to produce image
rollover and animation effects.
• JavaScript can interact with Java applets and other embedded objects that appear
in the browser. JavaScript code can read and write the properties of these applets
and objects and can also invoke any methods they define. This feature truly
allows JavaScript to script Java.
• As mentioned at the start of this section, JavaScript can perform arbitrary
computation. JavaScript has a floating-point data type, arithmetic operators that
work with it, and a full complement of standard floating-point mathematical
functions.
• The JavaScript Date object simplifies the process of computing and working with
dates and times.
• The Document object supports a property that specifies the last-modified date for
the current document. You can use it to automatically display a timestamp on any
document.
• JavaScript has a window.setTimeout( ) method that allows a block of arbitrary
JavaScript code to be executed some number of milliseconds in the future. This is
useful for building delays or repetitive actions into a JavaScript program. In
JavaScript 1.2, setTimeout( ) is augmented by another useful method called
setInterval( ).
• The Navigator object (named after the Netscape web browser, of course) has
variables that specify the name and version of the browser that is running, as well
as variables that identify the platform on which it is running. These variables
allow scripts to customize their behavior based on browser or platform, so that
they can take advantage of extra capabilities supported by some versions or work
around bugs that exist on some platforms.
• In client-side JavaScript 1.2, the Screen object provides information about the size
and color-depth of the monitor on which the web browser is being displayed.
• As of JavaScript 1.1, the scroll( ) method of the Window object allows
JavaScript programs to scroll windows in the X and Y dimensions. In JavaScript
1.2, this method is augmented by a host of others that allow browser windows to
be moved and resized.

1.6.7 What JavaScript Can't Do

Client-side JavaScript has an impressive list of capabilities. Note, however, that they are
confined to browser- and document-related tasks. Since client-side JavaScript is used in a
limited context, it does not have features that would be required for standalone languages:

• JavaScript does not have any graphics capabilities, except for the powerful ability
to dynamically generate HTML (including images, tables, frames, forms, fonts,
etc.) for the browser to display.
• For security reasons, client-side JavaScript does not allow the reading or writing
of files. Obviously, you wouldn't want to allow an untrusted program from any
random web site to run on your computer and rearrange your files!
• JavaScript does not support networking of any kind, except that it can cause the
browser to download arbitrary URLs and it can send the contents of HTML forms
across the network to server-side scripts and email addresses.

1.7 JavaScript Security


Any time that programs (such as JavaScript scripts, Visual Basic programs, or Microsoft
Word macros) are included within shared documents, particularly documents that are
transmitted over the Internet or by email, there is a potential for viruses or other
malicious programs. The designers of JavaScript were aware of these security issues and
took care not to give JavaScript programs the power to perform damaging acts. As
described previously, for example, client-side JavaScript programs cannot read local files
or perform networking operations.

Because of the complexity of the web-browser environment, however, a number of


security problems did arise in early browser versions. In Netscape 2, for example, it was
possible to write JavaScript code that could automatically steal the email address of any
visitor to a page containing the code and then automatically send email in the visitor's
name, without the visitor's knowledge or approval. This, and a number of other security
holes, have been fixed. Although there is no guarantee that other security holes will not
be found, most knowledgeable users are comfortable letting modern browsers run the
JavaScript code found in web pages. Chapter 21 contains a complete discussion of
security in client-side JavaScript.
1.8 Example: Computing Loan Payments with
JavaScript
Example 1-3 is a listing of a complete, nontrivial JavaScript program. The program
computes the monthly payment on a home mortgage or other loan, given the amount of
the loan, the interest rate, and the repayment period. As you can see, the program consists
of an HTML form made interactive with JavaScript code. Figure 1-3 shows what the
HTML form looks like when displayed in a web browser. But the figure can only capture
a static snapshot of the program. The addition of JavaScript code makes it dynamic:
whenever the user changes the amount of the loan, the interest rate, or the number of
payments, the JavaScript code recomputes the monthly payment, the total of all
payments, and the total interest paid over the lifetime of the loan.

Figure 1-3. A JavaScript loan payment calculator

The first half of the example is an HTML form, nicely formatted using an HTML table.
Note that several of the form elements define onchange or onclick event handlers. The
web browser triggers these event handlers when the user changes the input or clicks on
the Compute button displayed in the form. Note that in each case, the value of the event
handler attribute is a string of JavaScript code: calculate( ). When the event handler is
triggered, it executes this code, which causes it to call the function calculate( ).

The calculate( ) function is defined in the second half of the example, inside
<script> tags. The function reads the user's input from the form, does the math required
to compute the loan payments, and displays the results of these calculations using the
bottom three form elements.
Example 1-3 is simple, but it is worth taking the time to look at it carefully. You
shouldn't expect to understand all the JavaScript code at this point, but studying this
example should give you a good idea of what JavaScript programs look like, how event
handlers work, and how JavaScript code can be integrated with HTML forms. Note that
comments (in English) are included within HTML between <!-- and --> markers and
within JavaScript code in lines that begin with the characters //.

Example 1-3. Computing loan payments with JavaScript


<head><title>JavaScript Loan Calculator</title></head>
<body bgcolor="white">
<!--
This is an HTML form that allows the user to enter data and allows
JavaScript to display the results it computes back to the user. The
form elements are embedded in a table to improve their appearance.
The form itself is given the name "loandata", and the fields within
the form are given names such as "interest" and "years". These
field names are used in the JavaScript code that follows the form.
Note that some of the form elements define "onchange" or "onclick"
event handlers. These specify strings of JavaScript code to be
executed when the user enters data or clicks on a button.
-->
<form name="loandata">
<table>
<tr><td colspan="3"><b>Enter Loan Information:</b></td></tr>
<tr>
<td>1)</td>
<td>Amount of the loan (any currency):</td>
<td><input type="text" name="principal" size="12"
onchange="calculate();"></td>
</tr>
<tr>
<td>2)</td>
<td>Annual percentage rate of interest:</td>
<td><input type="text" name="interest" size="12"
onchange="calculate();"></td>
</tr>
<tr>
<td>3)</td>
<td>Repayment period in years:</td>
<td><input type="text" name="years" size="12"
onchange="calculate();"></td>
</tr>
<tr><td colspan="3">
<input type="button" value="Compute" onclick="calculate();">
</td></tr>
<tr><td colspan="3">
<b>Payment Information:</b>
</td></tr>
<tr>
<td>4)</td>
<td>Your monthly payment will be:</td>
<td><input type="text" name="payment" size="12"></td>
</tr>
<tr>
<td>5)</td>
<td>Your total payment will be:</td>
<td><input type="text" name="total" size="12"></td>
</tr>
<tr>
<td>6)</td>
<td>Your total interest payments will be:</td>
<td><input type="text" name="totalinterest" size="12"></td>
</tr>
</table>
</form>

<!--
This is the JavaScript program that makes the example work. Note that
this script defines the calculate() function called by the event
handlers in the form. The function refers to values in the form
fields using the names defined in the HTML code above.
-->
<script language="JavaScript">
function calculate() {
// Get the user's input from the form. Assume it is all valid.
// Convert interest from a percentage to a decimal, and convert
from
// an annual rate to a monthly rate. Convert payment period in
years
// to the number of monthly payments.
var principal = document.loandata.principal.value;
var interest = document.loandata.interest.value / 100 / 12;
var payments = document.loandata.years.value * 12;

// Now compute the monthly payment figure, using esoteric math.


var x = Math.pow(1 + interest, payments);
var monthly = (principal*x*interest)/(x-1);

// Check that the result is a finite number. If so, display the


results.
if (!isNaN(monthly) &&
(monthly != Number.POSITIVE_INFINITY) &&
(monthly != Number.NEGATIVE_INFINITY)) {

document.loandata.payment.value = round(monthly);
document.loandata.total.value = round(monthly * payments);
document.loandata.totalinterest.value =
round((monthly * payments) - principal);
}
// Otherwise, the user's input was probably invalid, so don't
// display anything.
else {
document.loandata.payment.value = "";
document.loandata.total.value = "";
document.loandata.totalinterest.value = "";
}
}

// This simple method rounds a number to two decimal places.


function round(x) {
return Math.round(x*100)/100;
}
</script>
</body>
</html>

1.9 Using the Rest of This Book


The rest of this book is in five parts. Part I, which immediately follows this chapter,
documents the core JavaScript language. Chapter 2 through Chapter 6 begin this section
with some bland but necessary reading -- these chapters cover the basic information you
need to understand when learning a new programming language:

• Chapter 2 explains the basic structure of the language.


• Chapter 3 documents the data types supported by JavaScript.
• Chapter 4 covers variables, variable scope, and related topics.
• Chapter 5 explains expressions in JavaScript and documents each of the operators
supported by JavaScript. Because JavaScript syntax is modeled on Java, which is,
in turn, modeled on C and C++, experienced C, C++, or Java programmers can
skim much of this chapter.
• Chapter 6 describes the syntax and usage of each of the JavaScript statements.
Again, experienced C, C++, and Java programmers can skim some, but not all, of
this chapter.

The next five chapters of this first section become more interesting. They still cover the
core of the JavaScript language, but they document parts of the language that will not
already be familiar to you even if you already know C or Java. These chapters must be
studied carefully if you want to really understand JavaScript:

• Chapter 7 documents how functions are defined, invoked, and manipulated in


JavaScript.
• Chapter 8 explains objects, the most important JavaScript data type. This chapter
discusses object-oriented programming in JavaScript and explains how you can
define your own classes of objects in JavaScript.
• Chapter 9 describes the creation and use of arrays in JavaScript.
• Chapter 10 explains how to use regular expressions in JavaScript to perform
pattern-matching and search-and-replace operations.
• Chapter 11 covers advanced topics that have not been covered elsewhere. You
can skip this chapter the first time through the book, but the material it contains is
important to understand if you want to become a JavaScript expert.

Part II explains client-side JavaScript. The chapters in this part document the web-
browser objects that are at the heart of client-side JavaScript and provide detailed
examples of their use. Any interesting JavaScript program running in a web browser will
rely heavily on features specific to the client side.

Here's what you'll find in Part II:


• Chapter 12 explains the integration of JavaScript with web browsers. It discusses
the web browser as a programming environment and explains the various ways in
which JavaScript is integrated into web pages for execution on the client side.
• Chapter 13 documents the most central and important object of client-side
JavaScript, the Window object, as well as several important window-related
objects.
• Chapter 14 explains the Document object and related objects that expose the
contents of an HTML document to JavaScript code.
• Chapter 15 documents the Form object, which represents HTML forms. It also
documents the various form element objects that appear within HTML forms and
shows examples of JavaScript programming using forms.
• Chapter 16 illustrates the use of cookies to save state in web programming.
• Chapter 17 explains the core pieces of the W3C DOM standard and shows how a
JavaScript script can access any element of an HTML document.
• Chapter 18 explains the portions of the W3C DOM standard that allow a
JavaScript program to manipulate the style, appearance, and position of the
elements within an HTML document. This chapter shows how you can create
many DHTML effects with CSS properties.
• Chapter 19 covers JavaScript events and event handlers, which are central to all
JavaScript programs that interact with the user. This chapter covers the traditional
event model, the W3C DOM standard event model, and the Internet Explorer
proprietary event model.
• Chapter 20 explores the important issue of compatibility in JavaScript
programming and discusses techniques you can use to write JavaScript programs
that run correctly (or fail gracefully) on a wide variety of web browsers.
• Chapter 21 enumerates the security restrictions built into client-side JavaScript
and explains the rationale for them.
• Chapter 22 explains how you can use JavaScript to communicate with and control
Java applets. It also covers how you can do the reverse -- invoke JavaScript code
from Java applets.

Part III, Part IV, and Part V are reference sections that document the objects defined by
the core JavaScript language, the objects defined in traditional client-side JavaScript
programming, and the objects defined by the new W3C DOM standard, respectively.

1.10 Exploring JavaScript


The way to really learn a new programming language is to write programs with it. As you
read through this book, I encourage you to try out JavaScript features as you learn about
them. There are a number of techniques that make it easy to experiment with JavaScript.

The most obvious way to explore JavaScript is to write simple scripts. One of the nice
things about client-side JavaScript is that anyone with a web browser and a simple text
editor has a complete development environment; there is no need to buy or download
special-purpose software in order to begin writing JavaScript scripts. We saw an example
that computed factorials at the beginning of this chapter. Suppose you wanted to modify
it as follows to display Fibonacci numbers instead:

<script>
document.write("<h2>Table of Fibonacci Numbers</h2>");
for (i=0, j=1, k=0, fib =0; i<50; i++, fib=j+k, j=k, k=fib){
document.write("Fibonacci (" + i + ") = " + fib);
document.write("<br>");
}
</script>

This code may be convoluted (and don't worry if you don't yet understand it), but the
point is that when you want to experiment with short programs like this, you can simply
type them up and try them out in your web browser using a local file: URL. Note that
the code uses the document.write( ) method to display its HTML output, so that you
can see the results of its computations. This is an important technique for experimenting
with JavaScript. As an alternative, you can also use the alert( ) method to display
plain-text output in a dialog box:

alert("Fibonacci (" + i + ") = " + fib);

Note also that for simple JavaScript experiments like this, you can usually omit the
<html>, <head>, and <body> tags in your HTML file.

For even simpler experiments with JavaScript, you can sometimes use the javascript:
URL pseudoprotocol to evaluate a JavaScript expression and return the result. A
JavaScript URL consists of the javascript: protocol specifier followed by arbitrary
JavaScript code (with statements separated from one another by semicolons). When the
browser loads such a URL, it executes the JavaScript code. The value of the last
expression in such a URL is converted to a string, and this string is displayed by the web
browser as its new document. For example, you might type the following JavaScript
URLs into the Location field of your web browser to test your understanding of some of
JavaScript's operators and statements:

javascript:5%2
javascript:x = 3; (x < 5)? "x is less": "x is greater"
javascript:d = new Date( ); typeof d;
javascript:for(i=0,j=1,k=0,fib=1; i<10; i++,fib=j+k,k=j,j=fib)
alert(fib);
javascript:s=""; for(i in document) s+=i+":"+document[i]+"\n";
alert(s);

While exploring JavaScript, you'll probably write code that doesn't work as you expect it
to and want to debug it. The basic debugging technique for JavaScript is like that in many
other languages: insert statements into your code to print out the values of relevant
variables so that you can try to figure out what is actually happening. As we've seen, you
can sometimes use the document.write( ) method to do this. This method doesn't work
from within event handlers, however, and has some other shortcomings as well, so it's
often easier to use the alert( ) function to display debugging messages in a separate
dialog box.

The for/in loop (described in Chapter 6) is also useful for debugging. You can use it,
along with the alert( ) method, to write a function that displays a list of the names and
values of all properties of an object, for example. This kind of function can be handy
when exploring the language or trying to debug code.

Good luck with JavaScript, and have fun exploring!


Part I: Core JavaScript
This part of the book, Chapter 2 through Chapter 11, documents the core JavaScript
language as it is used in web browsers, web servers, and other embedded JavaScript
implementations. This part is meant to be a JavaScript language reference. After you read
through it once to learn the language, you may find yourself referring back to it to refresh
your memory about some of the trickier points of JavaScript.

• Chapter 2
• Chapter 3
• Chapter 4
• Chapter 5
• Chapter 6
• Chapter 7
• Chapter 8
• Chapter 9
• Chapter 10
• Chapter 11
Chapter 2. Lexical Structure
The lexical structure of a programming language is the set of elementary rules that
specifies how you write programs in that language. It is the lowest-level syntax of a
language; it specifies such things as what variable names look like, what characters are
used for comments, and how one program statement is separated from the next. This
short chapter documents the lexical structure of JavaScript.

2.1 Character Set


JavaScript programs are written using the Unicode character set. Unlike the 7-bit ASCII
encoding, which is useful only for English, and the 8-bit ISO Latin-1 encoding, which is
useful only for English and major Western European languages, the 16-bit Unicode
encoding can represent virtually every written language in common use on the planet.
This is an important feature for internationalization and is particularly important for
programmers who do not speak English.

American and other English-speaking programmers typically write programs using a text
editor that supports only the ASCII or Latin-1 character encodings, and thus they don't
have easy access to the full Unicode character set. This is not a problem, however,
because both the ASCII and Latin-1 encodings are subsets of Unicode, so any JavaScript
program written using those character sets is perfectly valid. Programmers who are used
to thinking of characters as 8-bit quantities may be disconcerted to know that JavaScript
represents each character using 2 bytes, but this fact is actually transparent to the
programmer and can simply be ignored.

Although the ECMAScript v3 standard allows Unicode characters anywhere in a


JavaScript program, Versions 1 and 2 of the standard allow Unicode characters only in
comments and quoted string literals -- all other parts of an ECMAScript v1 program are
restricted to the ASCII character set. Versions of JavaScript that predate ECMAScript
standardization typically do not support Unicode at all.

2.2 Case Sensitivity


JavaScript is a case-sensitive language. This means that language keywords, variables,
function names, and any other identifiers must always be typed with a consistent
capitalization of letters. The while keyword, for example, must be typed "while", not
"While" or "WHILE". Similarly, online, Online, OnLine, and ONLINE are four distinct
variable names.

Note, however, that HTML is not case-sensitive. Because of its close association with
client-side JavaScript, this difference can be confusing. Many JavaScript objects and
properties have the same names as the HTML tags and attributes they represent. While
these tags and attribute names can be typed in any case in HTML, in JavaScript they
typically must be all lowercase. For example, the HTML onclick event handler attribute
is commonly specified as onClick in HTML, but it must be referred to as onclick in
JavaScript code.

While core JavaScript is entirely and exclusively case-sensitive, exceptions to this rule
are allowed in client-side JavaScript. In Internet Explorer 3, for example, all client-side
objects and properties were case-insensitive. This caused problematic incompatibilities
with Netscape, however, so in Internet Explorer 4 and later, client-side objects and
properties are case-sensitive.

2.3 Whitespace and Line Breaks


JavaScript ignores spaces, tabs, and newlines that appear between tokens in programs,
except those that are part of string or regular expression literals. A token is a keyword,
variable name, number, function name, or some other entity in which you would
obviously not want to insert a space or a line break. If you place a space, tab, or newline
within a token, you break it up into two tokens -- thus, 123 is a single numeric token, but
12 3 is two separate tokens (and constitutes a syntax error, incidentally).

Because you can use spaces, tabs, and newlines freely in your programs (except in
strings, regular expressions, and tokens), you are free to format and indent your programs
in a neat and consistent way that makes the code easy to read and understand. Note,
however, that there is one minor restriction on the placement of line breaks; it is
described in the following section.

2.4 Optional Semicolons


Simple statements in JavaScript are generally followed by semicolons (;), just as they are
in C, C++, and Java. The semicolon serves to separate statements from each other. In
JavaScript, however, you may omit the semicolon if each of your statements is placed on
a separate line. For example, the following code could be written without semicolons:

a = 3;
b = 4;

But when formatted as follows, the first semicolon is required:

a = 3; b = 4;

Omitting semicolons is not a good programming practice; you should get in the habit of
using them.

Although JavaScript theoretically allows line breaks between any two tokens, the fact
that JavaScript automatically inserts semicolons for you causes some exceptions to this
rule. Loosely, if you break a line of code in such a way that the line before the break
appears to be a complete statement, JavaScript may think you omitted the semicolon and
insert one for you, altering your meaning. Some places you should look out for this are
with the return, break, and continue statements (which are described in Chapter 6).
For example, consider the following:

return
true;

JavaScript assumes you meant:

return;
true;

However, you probably meant:

return true;

This is something to watch out for -- this code does not cause a syntax error and will fail
in a nonobvious way. A similar problem occurs if you write:

break
outerloop;

JavaScript inserts a semicolon after the break keyword, causing a syntax error when it
tries to interpret the next line. For similar reasons, the ++ and -- postfix operators (see
Chapter 5) must always appear on the same line as the expressions to which they are
applied.

2.5 Comments
JavaScript, like Java, supports both C++ and C-style comments. Any text between a //
and the end of a line is treated as a comment and is ignored by JavaScript. Any text
between the characters /* and */ is also treated as a comment. These C-style comments
may span multiple lines but may not be nested. The following lines of code are all legal
JavaScript comments:

// This is a single-line comment.


/* This is also a comment */ // and here is another comment.
/*
* This is yet another comment.
* It has multiple lines.
*/
2.6 Literals
A literal is a data value that appears directly in a program. The following are all literals:

12 // The number twelve


1.2 // The number one point two
"hello world" // A string of text
'Hi' // Another string
true // A boolean value
false // The other boolean value
/javascript/gi // A "regular expression" literal (for pattern
matching)
null // Absence of an object

In ECMAScript v3, expressions that serve as array and object literals are also supported.
For example:

{ x:1, y:2 } // An object initializer


[1,2,3,4,5] // An array initializer

Note that these array and object literals have been supported since JavaScript 1.2 but
were not standardized until ECMAScript v3.

Literals are an important part of any programming language, as it is impossible to write a


program without them. The various JavaScript literals are described in detail in Chapter
3.

2.7 Identifiers
An identifier is simply a name. In JavaScript, identifiers are used to name variables and
functions and to provide labels for certain loops in JavaScript code. The rules for legal
identifier names are the same in JavaScript as they are in Java and many other languages.
The first character must be a letter, an underscore (_), or a dollar sign ($).[1] Subsequent
characters may be any letter or digit or an underscore or dollar sign. (Numbers are not
allowed as the first character so that JavaScript can easily distinguish identifiers from
numbers.) These are all legal identifiers:
[1]
Note that dollar signs are not legal in identifiers prior to JavaScript 1.1. They are intended for use only by code-generation tools, so you
should avoid using dollar signs in identifiers in the code you write yourself.

i
my_variable_name
v13
_dummy
$str
In ECMAScript v3, identifiers can contain letters and digits from the complete Unicode
character set. Prior to this version of the standard, JavaScript identifiers are restricted to
the ASCII character set. ECMAScript v3 also allows Unicode escape sequences to appear
in identifiers. A Unicode escape is the characters \u followed by 4 hexadecimal digits
that specify a 16-bit character encoding. For example, the identifier could also be
written as \u03c0. Although this is an awkward syntax, it makes it possible to translate
JavaScript programs that contain Unicode characters into a form that allows them to be
manipulated with text editors and other tools that do not support the full Unicode
character set.

Finally, identifiers cannot be the same as any of the keywords used for other purposes in
JavaScript. The next section lists the special names that are reserved in JavaScript.

2.8 Reserved Words


There are a number of reserved words in JavaScript. These are words that you cannot use
as identifiers (variable names, function names, and loop labels) in your JavaScript
programs. Table 2-1 lists the keywords standardized by ECMAScript v3. These words
have special meaning to JavaScript -- they are part of the language syntax itself.

Table 2-1. Reserved JavaScript keywords


break do if switch typeof
case else in this var
catch false instanceof throw void
continue finally new true while
default for null try with
delete function return

Table 2-2 lists other reserved keywords. These words are not currently used in
JavaScript, but they are reserved by ECMAScript v3 as possible future extensions to the
language.

Table 2-2. Words reserved for ECMA extensions


abstract double goto native static
boolean enum implements package super
byte export import private synchronized
char extends int protected throws
Table 2-2. Words reserved for ECMA extensions
abstract double goto native static
class final interface public transient
const float long short volatile

debugger

In addition to some of the formally reserved words just listed, current drafts of the
ECMAScript v4 standard are contemplating the use of the keywords as, is, namespace,
and use. Current JavaScript interpreters will not prevent you from using these four words
as identifiers, but you should avoid them anyway.

You should also avoid using as identifiers the names of global variables and functions
that are predefined by JavaScript. If you create variables or functions with these names,
either you will get an error (if the property is read-only) or you will redefine the existing
variable or function -- something you should not do unless you know exactly what you're
doing. Table 2-3 lists global variables and functions defined by the ECMAScript v3
standard. Specific implementations may define other global properties, and each specific
JavaScript embedding (client-side, server-side, etc.) will have its own extensive list of
global properties.[2]
[2]
See the Window object in the client-side reference section of this book for a list of the additional global variables and functions defined by
client-side JavaScript.

Table 2-3. Other identifiers to avoid


arguments encodeURI Infinity Object String
Array Error isFinite parseFloat SyntaxError
Boolean escape isNaN parseInt TypeError
Date eval Math RangeError undefined
decodeURI EvalError NaN ReferenceError unescape
decodeURIComponent Function Number RegExp URIError
Chapter 3. Data Types and Values
Computer programs work by manipulating values , such as the number 3.14 or the text
"Hello World". The types of values that can be represented and manipulated in a
programming language are known as data types, and one of the most fundamental
characteristics of a programming language is the set of data types it supports. JavaScript
allows you to work with three primitive data types: numbers, strings of text (known as
"strings"), and boolean truth values (known as "booleans"). JavaScript also defines two
trivial data types, null and undefined, each of which defines only a single value.

In addition to these primitive data types, JavaScript supports a composite data type
known as object. An object (that is, a member of the data type object) represents a
collection of values (either primitive values, like numbers and strings, or composite
values, like other objects). Objects in JavaScript have a dual nature: an object can
represent an unordered collection of named values or an ordered collection of numbered
values. In the latter case, the object is called an array . Although objects and arrays are
fundamentally the same data type in JavaScript, they behave quite differently and will
usually be considered distinct types throughout this book.

JavaScript defines another special kind of object, known as a function . A function is an


object that has executable code associated with it. A function may be invoked to perform
some kind of operation. Like arrays, functions behave differently from other kinds of
objects, and JavaScript defines special language syntax for working with them. Thus,
we'll treat the function data type independently of the object and array types.

In addition to functions and arrays, core JavaScript defines a few other specialized kinds
of objects. These objects do not represent new data types, just new classes of objects. The
Date class defines objects that represent dates, the RegExp class defines objects that
represent regular expressions (a powerful pattern-matching tool described in Chapter 10),
and the Error class defines objects that represent syntax and runtime errors that can occur
in a JavaScript program.

The remainder of this chapter documents each of the primitive data types in detail. It also
introduces the object, array, and function data types, which are fully documented in
Chapter 7, Chapter 8, and Chapter 9. Finally, it provides an overview of the Date,
RegExp, and Error classes, which are documented in full detail in the core reference
section of this book.

3.1 Numbers
Numbers are the most basic data type; they require very little explanation. JavaScript
differs from programming languages such as C and Java in that it does not make a
distinction between integer values and floating-point values. All numbers in JavaScript
are represented as floating-point values. JavaScript represents numbers using the 64-bit
floating-point format defined by the IEEE 754 standard,[1] which means it can represent
numbers as large as ±1.7976931348623157 x 10308 and as small as ±5 x 10 -324.
[1]
This format should be familiar to Java programmers as the format of the double type. It is also the double format used in almost all
modern implementations of C and C++.

When a number appears directly in a JavaScript program, we call it a numeric literal.


JavaScript supports numeric literals in several formats, as described in the following
sections. Note that any numeric literal can be preceded by a minus sign (-) to make the
number negative. Technically, however, - is the unary negation operator (see Chapter 5),
not part of the numeric literal syntax.

3.1.1 Integer Literals

In a JavaScript program, a base-10 integer is written as a sequence of digits. For example:

0
3
10000000

The JavaScript number format allows you to exactly represent all integers between -
9007199254740992 (-253) and 9007199254740992 (253), inclusive. If you use integer
values larger than this, you may lose precision in the trailing digits. Note, however, that
certain integer operations in JavaScript (in particular the bitwise operators described in
Chapter 5) are performed on 32-bit integers, which range from -2147483648 (-231) to
2147483647 (231 -1).

3.1.2 Hexadecimal and Octal Literals

In addition to base-10 integer literals, JavaScript recognizes hexadecimal (base-16)


values. A hexadecimal literal begins with "0x" or "0X", followed by a string of
hexadecimal digits. A hexadecimal digit is one of the digits 0 through 9 or the letters a (or
A) through f (or F), which are used to represent values 10 through 15. Examples of
hexadecimal integer literals are:

0xff // 15*16 + 15 = 255 (base 10)


0xCAFE911

Although the ECMAScript standard does not support them, some implementations of
JavaScript allow you to specify integer literals in octal (base-8) format. An octal literal
begins with the digit 0 and is followed by a sequence of digits, each between 0 and 7. For
example:

0377 // 3*64 + 7*8 + 7 = 255 (base 10)


write an integer literal with a leading zero -- you cannot know whether an implementation
will interpret it as an octal or decimal value.

3.1.3 Floating-Point Literals

Floating-point literals can have a decimal point; they use the traditional syntax for real
numbers. A real value is represented as the integral part of the number, followed by a
decimal point and the fractional part of the number.

Floating-point literals may also be represented using exponential notation: a real number
followed by the letter e (or E), followed by an optional plus or minus sign, followed by
an integer exponent. This notation represents the real number multiplied by 10 to the
power of the exponent.

More succinctly, the syntax is:

[digits][.digits][(E|e)[(+|-)]digits]

For example:

3.14
2345.789
.333333333333333333
6.02e23 // 6.02 x 1023
1.4738223E-32 // 1.4738223 x 10-32

Note that there are infinitely many real numbers, but only a finite number of them
(18437736874454810627, to be exact) can be represented exactly by the JavaScript
floating-point format. This means that when you're working with real numbers in
JavaScript, the representation of the number will often be an approximation of the actual
number. The approximation is usually good enough, however, and this is rarely a
practical problem.

3.1.4 Working with Numbers

JavaScript programs work with numbers using the arithmetic operators that the language
provides. These include + for addition, - for subtraction, * for multiplication, and / for
division. Full details on these and other arithmetic operators can be found in Chapter 5.

In addition to these basic arithmetic operations, JavaScript supports more complex


mathematical operations through a large number of mathematical functions that are a core
part of the language. For convenience, these functions are all stored as properties of a
single Math object, so we always use the literal name Math to access them. For example,
here's how to compute the sine of the numeric value x:
sine_of_x = Math.sin(x);

And to compute the square root of a numeric expression:

hypot = Math.sqrt(x*x + y*y);

See the Math object and subsequent listings in the core reference section of this book for
full details on all the mathematical functions supported by JavaScript.

There is also one interesting method that you can use with numbers. The toString( )
method converts an integer to a string, using the radix, or base, specified by its argument
(the base must be between 2 and 36). For example, to convert a number to binary, use
toString( ) like this:

var x = 33;
var y = x.toString(2); // y is "100001"

To invoke the toString( ) method on a number literal, you can use parentheses to
prevent the . from being interpreted as a decimal point:

var y = (257).toString(0x10); // y is "101"

3.1.5 Special Numeric Values

JavaScript uses several special numeric values. When a floating-point value becomes
larger than the largest representable finite number, the result is a special infinity value,
which JavaScript prints as Infinity. Similarly, when a negative value becomes lower
than the last representable negative number, the result is negative infinity, printed as -
Infinity.

Another special JavaScript numeric value is returned when a mathematical operation


(such as division of zero by zero) yields an undefined result or an error. In this case, the
result is the special not-a-number value, printed as NaN. The not-a-number value behaves
unusually: it does not compare equal to any number, including itself! For this reason, a
special function, isNaN( ), is required to test for this value. A related function,
isFinite( ) , tests whether a number is not NaN and is not positive or negative infinity.

Table 3-1 lists several constants that JavaScript defines to represent these special numeric
values.

Table 3-1. Special numeric constants


Constant Meaning
Infinity Special value to represent infinity
NaN Special not-a-number value
Number.MAX_VALUE Largest representable number
Number.MIN_VALUE Smallest (closest to zero) representable number
Number.NaN Special not-a-number value
Number.POSITIVE_INFINITY Special value to represent infinity
Number.NEGATIVE_INFINITY Special value to represent negative infinity

The Infinity and NaN constants are defined by the ECMAScript v1 standard and are not
implemented prior to JavaScript 1.3. The various Number constants, however, have been
implemented since JavaScript 1.1.

3.2 Strings
A string is a sequence of Unicode letters, digits, punctuation characters, and so on -- it is
the JavaScript data type for representing text. As you'll see shortly, you can include string
literals in your programs by enclosing them in matching pairs of single or double
quotation marks. Note that JavaScript does not have a character data type such as char,
like C, C++, and Java do. To represent a single character, you simply use a string that has
a length of 1.

3.2.1 String Literals

A string is a sequence of zero or more Unicode characters enclosed within single or


double quotes (' or "). Double-quote characters may be contained within strings
delimited by single-quote characters, and single-quote characters may be contained
within strings delimited by double quotes. String literals must be written on a single line;
they may not be broken across two lines. If you need to include a newline character in a
string literal, use the character sequence \n , which is documented in the next section.
Examples of string literals are:

"" // The empty string: it has zero characters


'testing'
"3.14"
'name="myform"'
"Wouldn't you prefer O'Reilly's book?"
"This string\nhas two lines"
"pi is the ratio of a circle's circumference to its diameter"
As illustrated in the last example string shown, the ECMAScript v1 standard allows
Unicode characters within string literals. Implementations prior to JavaScript 1.3,
however, typically support only ASCII or Latin-1 characters in strings. As we'll see in the
next section, you can also include Unicode characters in your string literals using special
"escape sequences." This is useful if your text editor does not provide complete Unicode
support.

Note that when you use single quotes to delimit your strings, you must be careful with
English contractions and possessives like can't and O'Reilly's. Since the apostrophe is the
same as the single-quote character, you must use the backslash character (\) to escape
any apostrophes that appear in single-quoted strings (this is explained in the next section).

In client-side JavaScript programming, JavaScript code often contains strings of HTML


code, and HTML code often contains strings of JavaScript code. Like JavaScript, HTML
uses either single or double quotes to delimit its strings. Thus, when combining
JavaScript and HTML, it is a good idea to use one style of quotes for JavaScript and the
other style for HTML. In the following example, the string "Thank you" is single-quoted
within a JavaScript expression, which is double-quoted within an HTML event handler
attribute:

<a href="" onclick="alert('Thank you')">Click Me</a>

3.2.2 Escape Sequences in String Literals

The backslash character (\) has a special purpose in JavaScript strings. Combined with
the character that follows it, it represents a character that is not otherwise representable
within the string. For example, \n is an escape sequence that represents a newline
character.[2]
[2]
C, C++, and Java programmers will already be familiar with this and other JavaScript escape sequences.

Another example, mentioned in the previous section, is the \' escape, which represents
the single quote (or apostrophe) character. This escape sequence is useful when you need
to include an apostrophe in a string literal that is contained within single quotes. You can
see why we call these escape sequences -- here, the backslash allows us to escape from
the usual interpretation of the single-quote character. Instead of using it to mark the end
of the string, we use it as an apostrophe:

'You\'re right, it can\'t be a quote'

Table 3-2 lists the JavaScript escape sequences and the characters they represent. Two of
the escape sequences are generic ones that can be used to represent any character by
specifying its Latin-1 or Unicode character code as a hexadecimal number. For example,
the sequence \xA9 represents the copyright symbol, which has the Latin-1 encoding
given by the hexadecimal number A9. Similarly, the \u escape represents an arbitrary
Unicode character specified by four hexadecimal digits. \u03c0 represents the character
, for example. Note that Unicode escapes are required by the ECMAScript v1 standard
but are not typically supported in implementations prior to JavaScript 1.3. Some
implementations of JavaScript also allow a Latin-1 character to be specified by three
octal digits following a backslash, but this escape sequence is not supported in the
ECMAScript v3 standard and should no longer be used.

Table 3-2. JavaScript escape sequences


Sequence Character represented
\0 The NUL character (\u0000).
\b Backspace (\u0008).
\t Horizontal tab (\u0009).
\n Newline (\u000A).
\v Vertical tab (\u000B).
\f Form feed (\u000C).
\r Carriage return (\u000D).
\" Double quote (\u0022).
\' Apostrophe or single quote (\u0027).
\\ Backslash (\u005C).
\xXX The Latin-1 character specified by the two hexadecimal digits XX.
\uXXXX The Unicode character specified by the four hexadecimal digits XXXX.

\XXX
The Latin-1 character specified by the octal digits XXX, between 1 and 377.
Not supported by ECMAScript v3; do not use this escape sequence.

Finally, note that the backslash escape cannot be used before a line break to continue a
string (or other JavaScript) token across two lines or to include a literal line break in a
string. If the \ character precedes any character other than those shown in Table 3-2, the
backslash is simply ignored (although future versions of the language may, of course,
define new escape sequences). For example, \# is the same thing as #.
3.2.3 Working with Strings

One of the built-in features of JavaScript is the ability to concatenate strings. If you use
the + operator with numbers, it adds them. But if you use this operator on strings, it joins
them by appending the second to the first. For example:

msg = "Hello, " + "world"; // Produces the string "Hello, world"


greeting = "Welcome to my home page," + " " + name;

To determine the length of a string -- the number of characters it contains -- use the
length property of the string. If the variable s contains a string, you access its length like
this:

s.length

You can use a number of methods to operate on strings. For example, to get the last
character of a string s:

last_char = s.charAt(s.length - 1)

To extract the second, third, and fourth characters from a string s:

sub = s.substring(1,4);

To find the position of the first letter a in a string s:

i = s.indexOf('a');

There are quite a few other methods that you can use to manipulate strings. You'll find
full documentation of these methods in the core reference section of this book, under the
String object and subsequent listings.

As you can tell from the previous examples, JavaScript strings (and JavaScript arrays, as
we'll see later) are indexed starting with zero. That is, the first character in a string is
character 0. C, C++, and Java programmers should be perfectly comfortable with this
convention, but programmers used to languages with 1-based strings and arrays may find
that it takes some getting used to.

In some implementations of JavaScript, individual characters can be read from strings


(but not written into strings) using array notation, so the earlier call to charAt( ) could
also be written like this:
Exploring the Variety of Random
Documents with Different Content
gestemd en zeide „mi góedoe pikíen mass’ra, san’ doe joe agen”. 183 „Mi
de síki, néne” 184 was dan het antwoord. Op verzoek van mijn moeder
zou néne mij wat afleiding bezorgen, door mij een anansi-tori te
vertellen. Eerst maakte zij eenige gebaren, haalde diep adem en toen
begon zij:

Vroeger waren al onze vaders hanen.….

Nu, een moeder had drie dochters; en de vader van die meisjes was
een haan, die in de struiken nabij het huis woonde. Wanneer Moeder
voeder had voor Vader, zong ze driemaal:

Kakkadoedel, kakkadoedel! 185


Iffi joe biérti, kom mi da. 186

Vader kwam dan te voorschijn en na den inwendigen mensch versterkt


te hebben, verdween hij weder in het struikgewas.

Op zekeren dag zou Mama inkoopen gaan doen in de stad. Het oudste
der meisjes, Mina geheeten, zou dien [324]dag voor Vader zorgen. Het
jongste kind werd naar school gezonden, en de twee anderen gingen
lekkernijen koopen met het geld, dat de moeder had gegeven, om eten
voor Vader te koopen.

Toen nu Vader vroeg, waar zijn middageten gebleven was, antwoordde


Jet, de tweede dochter, dat Mina bezig was met koken. Vader verdween
toen weêr in zijn struik.

De beide meisjes gingen nu beraadslagen, wat ze zouden doen.


Eindelijk kwamen ze overeen, Vader te slachten en hem Moeder als
spijs voor te zetten.

Zoo gezegd, zoo gedaan.

Mina zong driemaal:

Kakkadoedel, kakkadoedel!
Iffi joe biérti, kom mi da!

Vader verscheen als gewoonlijk. Hij werd gevangen genomen en


geslacht. Inmiddels kwam het jongste kind uit school en vond hare
zusters druk bezig, in een kuil achter de keuken veêren te begraven. Zij
mocht Moeder niets vertellen van hetgeen zij gezien had. Vader werd in
de soep gekookt en de kinderen smulden naar hartelust.

Toen Moeder thuis kwam en naar Vader vroeg, antwoordde Mina:

„Eenige makkers zijn Vader komen halen, om te gaan kaarten”.

Toen was Moeder gerust. Ze kreeg haar aandeel van de soep, maar
kon toch niet eten. Het was alsof ze een voorgevoel had, dat het Vaders
vleesch was.

Het jongste dochtertje had evenwel verklaard, dat toen ze thuis kwam,
Mina en Jet bezig waren veêren te begraven in een kuil achter de
keuken.

Moeder vatte toen argwaan. Ze vroeg Mina of hetgeen ze haar als maal
had voorgezet Vaders vleesch niet was. Mina antwoordde natuurlijk
ontkennend. [325]

Doch toen Vader weken wegbleef en maar niet terugkwam, werd


Moeder boos op Mina.

Leisah, de jongste, ten einde raad, liep naar de rivier en zong:

Papà kári mi Leisah, 187


Mamà kári mi Leisah,
Mina kári mi Skoema! 188

Moeder liep haar na, maar zij kon haar kind nog slechts bij het haar
grijpen. Leisah verdronk en Moeder behield eenige strepen in de palm
harer hand.
Arme Leisah!

Sedert dien tijd hebben alle menschen strepen in de palm van de hand.

No. 27. Legende van Leisah. II.

Er wordt verhaald, dat in zeker dorp twee echtelieden woonden, die dol
waren op kinderen, maar er zelf geen hadden.

We moeten trachten, op welke wijze dan ook, aan een kind te komen,
zeiden zij.

Eens kwam een oude vrouw bij hen aan huis, vroeg de vrouw naar haar
welstand en naar dien van haren echtgenoot. De vrouw des huizes
antwoordde met droevige stem:

„Wij zijn, met Godswil, wel”.

„Wat scheelt U dan, Mevrouw?” vroeg de oude.

De vrouw des huizes deelde hare grieven mede, waarna de oude vrouw
haar een wees van acht dagen in handen gaf.

Het kind behoorde tot de vrouwelijke kunne en kreeg den naam van
Jacoba. Zij werd opgevoed als kind des huizes. [326]Toen zij twaalf jaar
was, moest ze voor huishoudelijke bezigheden beginnen te zorgen,
hetgeen zij met vlijt deed.

Eens wandelden de twee kinderliefhebbers langs het strand. Daar


zagen ze een meisje onbeheerd liggen en zij vroegen haar het een en
ander.
Daar zagen zij een meisje onbeheerd zitten …—Zie blz. 326.
Het kind werd naar huis medegenomen en kreeg den naam van Leisah.
Spoedig werd zij het troetelkindje, waarom Coba, hierover jaloersch,
haar begon uit te schelden.

De vondelinge begon te kwijnen van verdriet, omdat Coba haar


aanhoudend plaagde en treiterde.

Van dat alles vermoeid, zong zij het navolgende, waaruit haar
voornemen bleek:

Papà kári mi Leisah,


Mamà kári mi Leisah,
Coba kári mi Skóema.
Skoema mi na, Skóema mi sa tan! 189

De arme Coba werd weggejaagd, maar Leisah hield niet op met


treuren, en op zekeren dag keerde zij terug naar de plaats, waar zij
gevonden werd.

Haar pleegmoeder liep haar na als een pijl uit den boog, maar kon haar
niet inhalen.

Leisah was reeds in het water gesprongen, toen haar moeder


aankwam. Wel werd zij nog bij het lange haar gegrepen, maar door de
zwaarte zakte zij hoe langer hoe dieper en werd zij onder de golven
begraven. Zoo was Leisah weêr naar haar land teruggekeerd, omdat zij
uit schuim geboren was. De moeder, die haar troetelkind eindelijk had
moeten loslaten, hield de striemen van het haar in de hand. [327]

No. 28. Verhaal van het land van „Moeder Soemba”.

Er wordt verhaald, dat in een dorp een moeder met hare dochter
woonde en dat zij tot buren een moeder en dochter hadden, die zeer
wangunstig waren.
Het eerste meisje was allemansvriend; zij werd door iedereen bemind
en heette Akoeba 190 (Jacoba).

Akoeba nam haar buurmeisje Afi 191 tot vriendin aan, maar deze
benijdde haar in alles.

Eens kwam een oude vrouw bij Akoeba en gaf haar een kalebas ten
geschenke, zeggende:

„Ik ben een arm mensch; ik bezit niets op aarde, dat waarde heeft om
het U als geschenk aan te bieden; daarom hoop ik, dat ge deze
kleinigheid aan zult nemen, alsof het een kostbaar geschenk van een
rijk man was. Maar, mijn kind, deze kalebas moet gewasschen worden
in het land van ’Ma Soemba, opdat hij U gehoorzame.

Dat land is niet ver van hier, maar de wegen, die daarheen leiden, zijn
schier onbekend, daar er geen andere menschen wonen, dan ’Ma
Soemba zelve, die den sleutel aller tooverformulieren in handen heeft.

Het is niet gemakkelijk, ’Ma Soemba te naderen, als men niet vooraf is
ingelicht door betrouwbare personen.

Ge gaat van hieruit rechtdoor, tot daar, waar de weg zich in tweeën
splitst: de eene kant is schoon, de andere vuil.

Beloop den vuilen weg; aan het einde zult gij ’Ma Soemba vinden. Zij
zal U spreken en indien zij U iets vraagt, moet ge gehoorzamen, dan zal
ze Uwe kalebas wasschen, hoor, jonge dame!

Wanneer ge vreemde dingen ziet onderweg, spot er niet mede, maar


zing het lied, dat ik U zal leeren, nadat ge gevraagd zult hebben, om
voorbij te mogen gaan”.

Na verloop van een week ondernam Akoeba de reis, naar [328]de


aanwijzingen der oude vrouw. Toen zij een eind op weg was, zag zij
twee kankantries*, die aan het vechten waren.
Zij hielden op en het meisje ging voorbij, zingende:

Doegwèh a doegwèh, o! 192


Mi de bégi mi papà, mi passà 193
Doegwèh a doegwèh, o!

Zij liep door en zag twee voeten vechten. Ze verzocht en kreeg verlof,
door te gaan, onder het zingen van haar lied.

Iets verder trof Akoeba twee mátta’s* vechtende aan. Zij vroeg om door
te mogen gaan, hetgeen haar werd toegestaan, toen ze met haar lied
een aanvang maakte.

Eindelijk kwam zij aan het punt, waar de weg zich in tweeën splitste; de
eene zijweg was schoon, de andere vuil en onbegaanbaar.

Zij betrad den weg, die haar was aangewezen en zag vóór een huis een
vrouw, ’Ma Soemba, vol wonden en schurft zitten.

„Wat kom je hier doen!” vroeg zij aan het meisje. „Wees zoo goed en
wasch mij mijn rug af; er is water achter het huis”.

Akoeba waschte haar rug schoon, waardoor zij hare handen vol bloed
kreeg van de vele open wonden.

„Wasch je handen af en geef mij je kalebas, dan zal ik haar voor je


wasschen!” vervolgde de vrouw.

’Ma Soemba waschte de kalebas en gaf haar Akoeba terug.

„Keer nu naar huis terug en je zult je loon ontvangen. Bewaar je kalebas


goed en vrede zij verder met U”.

Het meisje vertrok en was na eenige uren weder thuis.

Of haar onderweg, bij het naar huis gaan, iets overkwam, wordt niet
verteld. [329]
Haar moeder wachtte haar met ongeduld en vroeg, of zij succes had
gehad.

„Ja!” antwoordde Akoeba.

Na eenige dagen kwam Afi haar vriendin bezoeken, terwijl deze juist
bezig was, haar kalebas te probeeren, waaruit zij tot hare groote
verbazing tal van gouden, zilveren en andere waardevolle voorwerpen
zag te voorschijn komen.
… waaruit zij tot hare groote verbazing tal van gouden, zilveren
en andere waardevolle voorwerpen zag te voorschijn komen.—
Zie blz. 329.

Het wangunstige buurmeisje vroeg haar naar de herkomst, daar zij al


dat moois ook wel graag zou willen hebben.

Akoeba vertelde hare vriendin alles en leerde haar ook het lied.

Den volgenden dag, reeds vóór zonsopgang, ondernam Afi den tocht.

Toen zij de verschillende karikaturen tegenkwam, dreef zij den spot er


meê.

Deze vervloekten haar, zeggende:

„Loop en gij zult vinden!”

Zij bereikte de splitsing van den weg en daar begon zij hare vriendin op
de onbehoorlijkste wijze uit te schelden.

„Zij dacht mij wat op de mouw te spelden, maar ik ben wijzer, dan ze
denkt. Het is uit wangunst, dat ze mij heeft gezegd, dien vuilen weg te
loopen. Zij wil niet, dat ik in haar geluk zal deelen. Ja! Zoo zijn de
menschen!—Maar ik neem dien schoonen weg.”

Op het einde gekomen, trof zij ’Ma Soemba aan, bezig obia 194 te koken.

’Ma Soemba verzocht haar, haar te willen wasschen, maar de juffer


begon haar uit te schelden.

„Geef me Uwe kalebas, dan zal ik haar uitwasschen; vrees niets”, zei de
vrouw. [330]

Doch juffer Afi bedankte haar niet eens, doch zei slechts: „Geef mij mijn
kalebas terug, want je maakt haar weêr vuil met jou handen”.
Vol blijdschap kwam zij weêr thuis bij moeder, die haar dadelijk vroeg, of
alles in orde was.

„Zeker, Mama, onze buurvrouw wilde mij misleiden, maar ik ben wijzer
dan ze denkt.

Ik ben klaar gekomen en zal haar bewijzen, dat niet alleen zij in ’t bezit
is van een wonderkalebas”.

Toen zij nog denzelfden dag het voorwerp raadpleegde, weigerde het;
het gaf geen resultaat. Haar vriendin ried haar toen aan, de kalebas
slechts in geval van nood te gebruiken. Doch Afi antwoordde, dat ze
geld noodig had en begon andermaal haar kalebas te raadplegen. Toen
kwam er allerlei ongedierte uit te voorschijn, dat haar doodde.

Zoo wordt het spreekwoord weêr bewaard:

Ba’ sóekoe, ba’ fínni, ba’ tjári. 195

No. 29. Boen no habi tangi.

Ondank is ’s werelds loon! Dat wil zeggen: boen no hábi tangì.

Er was eens een koning, die een zoon had, dien hij naar Holland had
gezonden, om te gaan leeren.

Doch toen de jongen terugkeerde, zei hij op zekeren dag:

„Vader, ik wil gaan wandelen, maar liefst alleen”.

„Het is goed, mijn jongen, gij kunt gaan”.

Den volgenden dag vertrok de jongen, en toen hij achter in den tuin
kwam, zag hij daar een dorren vijgeboom, die hem vroeg:
„Mijnheer, is het waar, dat ondank ’s werelds loon is?”

„Ik weet het niet”.

„Ja, het is waar, dat ondank ’s werelds loon is, want zie, ik heb aan uw
vader vruchten gegeven; hij heeft [331]mijne vruchten op brandewijn
gezet en ze gestoofd. En nu ben ik oud geworden; ik kan niet meer
bloeien en nu wil hij mij tot brandhout maken”.

De jongen erkende de waarheid dier woorden en antwoordde:

„Gij hebt gelijk”.

Toen trok de jongen verder en ontmoette een druivenboom, die den


jongen dezelfde vraag deed, en toen hij zijn wandeling vervolgde, kwam
hij langs een groot vuur met een slang er in, die blijkbaar in angst
verkeerde. En ook de slang vroeg aan den jongen, of het waar is, dat
ondank ’s werelds loon is. De jongen antwoordde niet, maar greep een
stok en nam de slang uit het vuur; doch nauwelijks had hij het dier
gered of het kroop tegen hem op en slingerde zich om zijn hals. De
slang wilde hem dooden.

„Van daag”, riep de jongen uit, „zie ik toch, dat ondank ’s werelds loon
is, want, kijk, ik heb u uit het vuur genomen en nu wilt ge mij dooden”.

Doch daar kwam juist een awari* voorbij, die dezelfde vraag tot den
jongen richtte, waarop deze antwoordde:

„Ja, het is waar, ondank is ’s werelds loon, want zie, ik heb de slang uit
het vuur genomen en nu wil ze mij dooden”.

„Ga mij wijzen”, hervatte Awari, „hoe gij de slang uit het vuur hebt
weggenomen”.

De slang kronkelde zich weêr om den stok en Awari gooide hem in het
vuur.
Daarop vervolgde Awari tegen den jongen:

„Laten wij heengaan en laat de slang in het vuur blijven”.

„Goed, doch dan moet gij met mij meê naar huis gaan; want ik wil mijn
vader en moeder wijzen, wie mij van den dood gered heeft”.

„Neen, dat doe ik niet, ik ben geen mensch; ik ben maar een dier”. [332]

Doch de jongen drong aan en zei: „ga meê”, waarop Awari


medegegaan is.

Thuis gekomen bij zijn vader en moeder, sprak de jongen tot Awari:

„Wel, Awari, wat wilt gij nu tot belooning hebben?”

„Niets wil ik hebben, maar als gij mij elken morgen een kip wilt geven,
dan ben ik tevreden”.

De koning zeide:

„Het is goed; kijk, hier heb ik een hok vol kippen; elken morgen kunt ge
er een komen halen”.

Maar dat beviel de koningin in het geheel niet; zij riep haar kokkin en
sprak tot haar:

„Morgen moet ge de awari dooden, want zoodoende raak ik al mijn


kippen kwijt”.

Den volgenden morgen kwam Awari, om de beloofde kip te halen, toen


de kokkin met een emmer water aankwam, die zij over de awari
omkeerde. En natuurlijk was Awari dood.

Hevig ontsteld en met heftige gebaren kwam de jongen toesnellen en


toen hij daar zijn redder dood zag liggen, riep hij uit:

„Het is toch een waar spreekwoord: boen no hábi tangì”.


No. 30. Geschiedenis van Kopro Kanon*.

Er was eens in een dorp een vrouw, die drie zoons had, waarvan de
oudste Mininimi heette, de tweede Krimintaria en de jongste Kopro
Kanon.

Zij had Mininimi en Krimintaria lief, maar Kopro Kanon niet; daarom
werd hij verwaarloosd en zat hij vol schurft 196 en jaws*. Als het etenstijd
was, riep de moeder alleen de twee ouden, zingende: [333]

Mininimi kom njam!


Krimintaria kom njam!
Kopro Kanon tan de! 197

Arme Kopro Kanon was stokmager en stonk van vuil. Zijn moeder wilde
niets van hem weten. Ach! Arme Kopro Kanon!

De twee oudste knapen zagen er rond uit van dikte.

De duivel, die menschenvleesch lust, had zijn oogen op hen gericht en


wachtte met ongeduld een gunstig oogenblik af, om hen te vangen.

Hij was juist op wacht, toen hij hoorde, op welke wijze de knapen
geroepen werden. Den volgenden dag kwam hij ter plaatse terug en
zong het lied met een heel grove stem.

Kopro Kanon had zijn broeders lief en zei hun:

„Gaat niet, want dat is de stem uwer moeder niet. Het komt mij voor, de
duivel te zijn”.

Zij waren hem gehoorzaam.

De duivel, die begreep, dat zijn zware stem de oorzaak was, dat de
jongens niet tot hem kwamen, ging toen bij een smid, om zijn tong te
laten vijlen.
De duivel … ging toen bij een smid om zijn tong te laten vijlen.—
Zie blz. 333.

De smid verbood zijn cliënt, bakoven* te eten, als zijn tong gevijld was,
daar zijn stem anders weêr grover zou worden.

„Ik zal aan Uw bevel voldoen”, antwoordde Joost hem.

Doch geen tien minuten van de smederij zijnde, ontmoette hij een
vrouw, die bakoven rondventte. De gulzigaard kon zijn lust niet
bedwingen en vroeg haar:

„Joe no séri mi toe sensi bakóeba?” 198

De bakove ging in één hap naar binnen.

Satan ging toen weêr de wacht houden en zong het lied met
donderende stem. [334]

De ongelukkige Kopro Kanon waarschuwde zijn broeders weêr om niet


te gaan, daar het slechts des duivels stem kon zijn, die zoo dreunend
en dof klonk.

De verdelger der wereld ging terug naar den smid, zonder eenig succes
te hebben gehad. Zijn stem was veranderd, daar zijn tong door bakove
vergiftigd was. De smid zei hem:

„Als iemand onder behandeling van een dokter is, moet hij diens
voorschriften opvolgen; anders loopt hij gevaar. Denk niet, dat een
patiënt den dokter kan foppen, neen, hij fopt zich zelf!”

„Maar, waarom zijt gij zoo hatelijk tegen mij?” vroeg Satan.

„Omdat ge vol leugens zit, vent. Ge spreekt tegen uw geweten.”

„Ben ik dan een leugenaar?”


„Een gevaarlijke ook. Denkt ge soms, dat ik niets anders te doen heb,
dan ieder oogenblik te zitten hameren en vijlen in uw bek?”

Na een flinke bestraffing begon de smid weêr te vijlen.

„Zing het lied nog eens, opdat ik U keure.”

De duivel zong.

„Hoe is het nu, goed niet waar?”

„Dank U vriendelijk, tot wederdienst”.

Satan ging naar zijn bestemming en begon met een altstem te zingen,
waardoor de twee knapen zijn slachtoffer werden. Toen de moeder hun
riep, antwoordde Kopro Kanon met droevige stem:

Mininimi no de,
Krimintaria no de,
Kopro Kanon wawán de. 199

[335]

De moeder ging toen naar Kopro Kanon, voedde hem van toen af en
verzorgde hem goed. Zij kwam te sterven en Kopro Kanon begroef
haar.

Wie kinderen heeft, mag het eene niet boven het andere voortrekken,
maar moet van allen evenveel houden.

No. 31. De Meermin of Watramama.

Er wordt verteld, dat het water beheerscht wordt door de


Watramama. 200
De Watramama is half mensch, half visch; zij heeft een zacht-gele tint
als een Indiaansche, een schoon gezicht, prachtige donkere oogen en
lang zwart haar.

De Watramama houdt verblijf in kreken. Zij komt nooit anders te


voorschijn dan om hare kleinen te zoogen of om zich het haar te
kammen met den wonderkam, en wel altijd met jongvloed 201. De
menschen, die het geluk hadden, haar te zien, vertellen dat het eene
Madonna is. Djokarto, van plantage „Pieterszorg”, zegt er een te
hebben gezien in een kreek van plantage „de Resolutie”. Zij zetelt onder
in de rivieren en vermag veel op de golven. Zij doet booten zinken en
eigent zich den inhoud toe. Nergens, bij niemand ter wereld, vindt men
zooveel rijkdommen als bij haar.

Men zegt, dat er menschen zijn, die de kunst verstaan, haar kam te
stelen, terwijl zij bezig is zich te kammen. Als de Watramama den dief
gevonden heeft, eischt zij haar kam terug en belooft in ruil een
aanzienlijke waarde aan geld. De dief echter paait haar met allerlei
beloften, en gebruikt haar om zoo te zeggen als een melkkoetje.
Telkens komt de Watramama terug en zij brengt steeds meer geld
mede, tot zij eindelijk het geluk heeft, haar kam terug te krijgen. Wil de
dief den kam niet teruggeven, [336]dan is hij verloren. Want de eerste
keer, dat hij over het water gaat, slaat zijn vaartuig om.

Er was eens iemand die, door een kreek varende, gekerm hoorde. Toen
hij voortparelde, bemerkte hij de Watramama, die in gevaar verkeerde
en hij verschafte haar hulp. De meermin zegende hem en beloofde hem
ten allen tijde haar bijstand. De man was visscher van beroep en deed
van toen af goede vangsten. Ook raadde zij hem aan, zijn pagala 202
open te laten, wanneer hij stadswaarts ging, en dagelijks vond hij er
geld in.

De Watramama had hem verboden met iemand hierover te spreken;


anders zou zij hem moeten straffen. 203 Maar ach! het zwakke geslacht,
dat de mannen zoo dikwijls in het verderf stort, bracht ook hem in het
ongeluk.

De man had vrouw en kinderen en toen de vrouw hem steeds met geld
thuis zag komen, vroeg zij naar de herkomst. Hij liet zich niet uit, doch
toen zij sterker aandrong en hij het, om de waarheid zeggen, niet meer
kon uithouden, vertelde hij haar alles en ook wat de gevolgen hiervan
zouden zijn.

Eens op een dag begaf de visscher zich naar een plantage, maar nog
eer hij op de plaats zijner bestemming was aangekomen, was hij
verdwenen.

Men zegt, dat het gevaarlijk is, de albino’s die nog al eens onder de
negers voorkomen, en Watramama-pikien 204 genoemd worden, veel
over het water te laten gaan, wanneer ze groot worden, daar de
Watramama ze dan wel eens tot zich neemt.

In den slaventijd was er een jonge neger-albino, Skroero-ki 205 genaamd,


die dikwijls op den rivierbodem [337]neêrdaalde, om allerlei voorwerpen
te halen. De Watramama was zijn vriendin. Hij ging bij haar eten en
bleef soms dagen onder water.

Zij had hem gewaarschuwd met niemand te spreken over hetgeen hij bij
haar hoorde of zag, maar Skroero-ki voldeed niet aan dat verzoek, en
toen hij weêr op den rivierbodem daalde, kwam hij niet meer aan de
oppervlakte terug.

Visschers, die hun bedrijf uitoefenen, vangen de Watramama wel eens


in hun netten.

Doch ze laten haar dan weêr gaan, daar ze anders gevaar zouden
loopen, om met boot en al in de diepte te verdwijnen!
No. 32. De Boa in de gedaante van een schoonen jongeling.

In zeer ouden tijd leefde een zeer mooi meisje. Haar schoonheid was
even beroemd, als haar trotschheid bekend was.

Van heinde en verre kwamen voorname jongelingen haar ten huwelijk


vragen, maar geen hunner keurde zij waardig genoeg, om haar
echtgenoot te worden.

Hare schatrijke ouders hadden daarover veel verdriet en zij spoorden


haar aanhoudend aan, om toch een dezer jongelingen te kiezen, daar
zij haar gaarne gehuwd wilden zien.

Maar het meisje hield staande, dat zij niet anders zou trouwen dan met
den man, dien zij lief had en dat zij er tot dusverre geen gezien had, die
hare liefde waardig was.

Op zekeren dag nam een reuzenslang, een boa*, een menschelijke


gedaante aan, kleedde zich als een schoone jongeling aan en begaf
zich naar de woning van het meisje.

Nauwelijks hief zij hare oogen op hem of zij werd zoodanig bekoord
door zijn schoonheid, dat zij bijna [338]flauw viel. Zij riep: „Vader, moeder,
hier is de man, dien ik bemin; en met hem wil ik trouwen”.

De ouders waren natuurlijk zeer verheugd, dat hun schoone dochter


eindelijk iemand naar haar zin gevonden had en alles werd zoo spoedig
mogelijk in gereedheid gebracht. Niets was kostbaar genoeg, om het
jonge paar te verschaffen.

De huwelijksfeesten duurden acht dagen lang. Zoo’n pracht was te


voren nooit gezien geweest.

Eindelijk moesten de jonggehuwden naar hunne nieuwe woning


trekken, die zoo prachtig mogelijk ingericht was.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookfinal.com

You might also like