100% found this document useful (9 votes)
79 views

Instant download JavaScript The Definitive Guide Fourth Edition Flanagan pdf all chapter

Definitive

Uploaded by

holubbuchyoj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (9 votes)
79 views

Instant download JavaScript The Definitive Guide Fourth Edition Flanagan pdf all chapter

Definitive

Uploaded by

holubbuchyoj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

Download the full version of the ebook at

https://ebookfinal.com

JavaScript The Definitive Guide Fourth


Edition Flanagan

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

Explore and download more ebook at https://ebookfinal.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

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/

ebookfinal.com

JavaScript Pocket Reference Third Edition David Flanagan

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

ebookfinal.com

Cassandra The Definitive Guide 3rd Edition Jeff Carpenter

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

ebookfinal.com

Elasticsearch The Definitive Guide 1st Edition Clinton


Gormley

https://ebookfinal.com/download/elasticsearch-the-definitive-
guide-1st-edition-clinton-gormley/

ebookfinal.com
Automotive Ethernet the Definitive Guide 1.2 Edition Bob
Metcalfe

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

ebookfinal.com

The Definitive Guide to HTML5 1st Edition Adam Freeman

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

ebookfinal.com

HTML XHTML The Definitive Guide Sixth Edition Chuck


Musciano

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

ebookfinal.com

Ethernet The Definitive Guide 2nd Edition Charles E.


Spurgeon

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

ebookfinal.com

Hadoop The Definitive Guide 4th ed Edition Tom White

https://ebookfinal.com/download/hadoop-the-definitive-guide-4th-ed-
edition-tom-white/

ebookfinal.com
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:
Random documents with unrelated
content Scribd suggests to you:
but the claims of that revelation, for proclaiming which he was now a
prisoner. So admirably did he conduct his whole plea, both for
himself and the cause of Christ, that in spite of the sneer of Festus,
Agrippa paid him the very highest compliment in his power, and
pronounced him to be utterly guiltless of the charges. No part of this
plea and its attendant discussions, needs to be recapitulated; but a
single characteristic of Paul, which is most strikingly evinced,
deserves especial notice. This is his profound regard for all the
established forms of polite address. He is not satisfied with a mere
respectful behavior towards his judges, but even distinguishes
himself by a minute observance of all the customary phrases of
politeness; nor does he suffer his courtly manner to be disturbed,
even by the abrupt remark of Festus, accusing him of frenzy. In his
reply, he styles his accuser “Most noble;” and yet every reader of
Jewish history knows, and Paul knew, that this Festus, to whom he
gave this honorable title, was one of the very wicked men of those
wicked times. The instance shows then, that those who, from
religious scruples, refuse to give the titles of established respect to
those who are elevated in station, and reject all forms of genteel
address, on the same ground, have certainly constructed their
system of practical religion on a model wholly different from that by
which the apostle’s demeanor was guided; and the whole impression
made on a common reader, by Luke’s clear statement of Paul’s
behavior before the most dignified and splendid audience that he
ever addressed, must be, that he was complete in all the forms and
observances of polite intercourse; and he must be considered, both
according to the high standard of his refined and dignified hearers,
and also by the universal standard of the refined of all ages,――not
only a finished, eloquent orator, but a person of polished manners,
delicate tact, ready compliment, and graceful, courtly address:――in
short, a perfect gentleman.

voyage to rome.

As Paul, however, had previously appealed to Caesar, his case


was already removed from any inferior jurisdiction, and his hearing
before Agrippa was intended only to gratify the king himself, and to
cause the particulars of his complicated case to be more fully drawn
out before his royal hearer, who was so accomplished in Hebrew
law, that his opinion was very naturally desired by Festus; for, as the
governor himself confessed, the technicalities and abstruse points
involved in the charge, were altogether beyond the comprehension
of a Roman judge, with a mere heathen education. The object,
therefore, of obtaining a full statement of particulars, to be presented
to his most august majesty, the emperor, being completely
accomplished by this hearing of Paul before Agrippa,――there was
now nothing to delay the reference of the case to Nero; and Paul
was therefore consigned, along with other prisoners of state, to the
care of a Roman officer, Julius, a centurion of the Augustan cohort.
Taking passage at Caesarea, in an Adramyttian vessel, Julius sailed
with his important charge from the shores of Palestine, late in the
year 60. Following the usual cautious course of all ancient
navigators,――along the shores, and from island to island, venturing
across the open sea only with the fairest winds,――the vessel which
bore the apostle on his first voyage to Italy, coasted along by Syria
and Asia Minor. Of those Christian associates who accompanied
Paul, none are known except Timothy, Luke, his graphically accurate
historian, and Aristarchus of Thessalonica, the apostle’s long-known
companion in travel. These, of course, were a source of great
enjoyment to Paul on this tedious voyage, surrounded, as he was,
otherwise, by strangers and heathen, by most of whom he must
have been regarded in the light of a mere criminal, held in bonds for
trial. He was, however, very fortunate in the character of the
centurion to whose keeping he was entrusted, as is shown in more
than one incident related by Luke. After one day’s sail, the vessel
touching at Sidon, Julius here politely gave Paul permission to visit
his Christian friends in that place,――thus conferring a great favor,
both on the apostle and on the church of Sidon. Leaving this place,
their course was next along the coast of Syria, and then eastwards,
along the southern shore of Asia Minor, keeping in the Cilician strait
between that province and the great island of Cyprus, on account of
the violence of the southwesters. Coasting along by Pamphylia and
Lycia, they next touched at Myra, a city in the latter province, where
they were obliged to take passage in another vessel, bound from
Alexandria to Italy. In this vessel, they also kept close to the coast,
their course being still retarded by head winds, until they reached
Cnidus, the farthest southeastern point of Asia Minor, and thence
stretched across the Carpathian sea, to Crete, approaching it first at
Cape Salmone, the most eastern point at the island, and then
passing on to a place called “the Fair Haven,” near Lasea, probably
one of the hundred cities of Crete, but mentioned in no other ancient
writer. At this place, Paul, whose experience in former voyages was
already considerable, having been twice ship-wrecked, had sagacity
enough to see that any further navigation that season would be
dangerous; for it was now the beginning of October, and the most
dreadful tempests might be reasonably expected on the wintry sea,
before they could reach the Italian coast. He warned the centurion
accordingly, of the peril to which all their lives were exposed; but the
owner and commander of the vessel, anxious to find a better place
for wintering than this, persuaded Julius to risk the passage to the
south side of the island, when they might find, in the port of Phoenix,
a more convenient winter harbor. So, after the south wind had nearly
died away, they attempted to take advantage of this apparent lull,
and work their way, close to the shore along the south side of Crete;
but presently they were caught by a tremendous Levanter, which
carried them with great velocity away to the west, to the island of
Clauda, which lies south of the west end of Crete. Here the danger
of the ship’s breaking in pieces was so great, that having with much
ado overhauled their boat, they undergirded the ship with cables, to
keep it together,――a measure not unknown in modern navigation.
Finding that they were in much danger of grounding among the
quicksands on the coast of the island, they were glad to stand out to
sea; and taking in all sail, scudded under bare poles for fourteen
days, during a great part of which time, they saw neither sun, moon
nor stars, the whole sky being constantly overcast with clouds, so
that they knew nothing of their position. The wind of course carried
them directly west, over what was then called the sea of
Adria,――not what is now called the Adriatic gulf, but that part of the
Mediterranean, which lies between Greece, Italy and Africa. In their
desperation, the passengers threw over their own baggage, to
lighten the ship; and they began to lose all hope of being saved from
shipwreck. Paul, however, encouraged them by the narration of a
dream, in which God had revealed to him that every one of them
should escape; and they still kept their hopes alive to the fourteenth
night, when the sailors, thinking that the long western course must
have brought them near Sicily, or the main-land of Italy, which lay not
far out of this direction, began to heave the lead, that they might
avoid the shore; and at the first sounding, found but twenty fathoms,
and at the next fifteen. Of course, the peril of grounding was
imminent, and they therefore cast anchor, and waited for day.
Knowing that they were now near some shore, the sailors
determined to provide for their own safety, and accordingly
undertook to let down the boat, to make their escape, and leave the
passengers to provide for themselves. But Paul represented to the
centurion the certainty of their destruction, if the ship should be left
without any seamen to manage it; and the soldiers of the prisoners’
guard, determined not to be thus deserted, though they should all
sink together, cut off the ropes by which the boat was held, and let it
fell off. All being thus inevitably committed to one doom, Paul
exhorted them to take food, and thus strengthen themselves for the
effort to reach the shore. They did so accordingly, and then, as a last
resort, flung out the wheat with which the ship was loaded, and at
day-break, when land appeared, seeing a small creek, they made an
effort to run the ship into it, weighing anchor and hoisting the
mainsail; but knowing nothing of the ground, soon struck, and the
overstrained ship was immediately broken by the waves, the bows
being fast in the sandbank, while the stern was heaved by every
surge. The soldiers, thinking first of their weighty charge, for whose
escape they were to answer with their lives, advised to kill them all,
lest they should swim ashore. But the more humane centurion
forbade it, and gave directions that every man should provide for his
own safety. They did so; and those that could not swim, clinging to
the fragments of the wreck, the whole two hundred and seventy-six
who were in the vessel, got safe to land.
“‘When sailing was now dangerous, because the fast was already past.’ verse 9. There
is no question but that this is the great fast of expiation, Leviticus xvi. 29, the description of
which we have in Isaiah lviii. under the name of a sabbath, verse 13. The precise time of
this sabbatic fast is on the tenth day of the seventh month, Tizri, which falls on the same
time very nearly with our September, the first day of Tizri on the seventh of that, and so the
10th of Tizri on the 16th of September, that is, thirteen days before our Michaelmas. This
being premised, the apostle’s reasoning becomes clear; for it is precisely the same as
though he should have said, because it was past the twentieth (the day Scaliger sets for the
solemnization of the fast,) of September; it being observed by all sailors, that for some
weeks before and after Michaelmas, there are on the sea sudden and frequent storms,
(probably the equinoctial,) which have in modern times received the name of Michaelmas
flaws, and must of course make sailing dangerous. Hesiod himself tells us, that at the going
down of Pleiades, which was at the end of autumn, navigation was hazardous.” (Williams.)

“Undergirding the ship.’ verse 17. We learn from various passages in the Greek and
Roman writers, that the ancients had recourse to this expedient, in order to save the ship
from imminent danger; and this method has been used in modern times. The process of
undergirding a ship is thus performed:――a stout cable is slipped under the vessel at the
prow, which can be conducted to any part of the ship’s keel, and then fasten the two ends
on the deck, to keep the planks from starting. An instance of this kind is mentioned in ‘Lord
Anson’s Voyage round the World.’ Speaking of a Spanish man-of-war in a storm, the writer
says, ‘They were obliged to throw overboard all their upper-deck guns, and take six turns of
the cable round the ship, to prevent her opening.’ (p. 24, 4to. edition.) Bp. Pearce and Dr.
Clarke, on Acts xxvii. 17. Two instances of undergirding the ship are noticed in the
‘Chevalier de Johnstone’s Memoirs of the Rebellion in 1745‒6, London, 1822, 8vo. pp. 421,
454.” (Williams’s notes on Pearson, p. 85.)
They now found that they had struck on the island of Melita, (now
Malta,) which lies just south of Sicily, in the direct track in which the
eastern gale must have blown them. The uncivilized inhabitants of
this desolate spot received the shipwrecked voyagers with the
kindest attention, and very considerately kindled a fire, to warm and
dry them, after their long soaking in cold water. The dripping apostle
took hold with the rest to make the fire blaze up, and gathered a
bundle of dry sticks, for the purpose; but with them he unconsciously
gathered a viper, which was sheltering itself among them from the
cold, and roused by the heat of the fire, now crept out upon his hand.
He, of course, as any other man would, gave a jerk, and shook it off,
as soon as he saw it,――a very natural occurrence; but the
superstitious barbarians thought this a perfect miracle, as they had
before foolishly considered it a token of divine wrath; and having
looked on him as an object of horror, and a wicked criminal, they
now, with equal sense, adored him as a God.

Another incident of more truly miraculous character, occurred to


Paul soon after, in the part of the island on which they were wrecked,
which had the effect of gaining him a much more solid fame. The
father of Publius, the Roman officer who governed the island, as the
deputy of the praetor of Sicily, was at that time very sick of the
dysentery; and Paul, going to see him, laid his hands on him and
prayed,――thus effecting a complete recovery. This being known,
other diseased persons were presented as the subjects of Paul’s
miraculous powers, and the same cures following his words, he with
his associates soon became the objects of a far more rational
reverence than had been excited by the deliverance from the viper.
The reverence too, was extended beyond mere empty honor. The
shipwrecked apostolic company having lost all their baggage and
provisions, were abundantly provided with everything that they
needed, by the grateful contributions of the islanders;――and when,
after a stay of three months, Paul and his companions departed,
they were loaded with things necessary for the voyage.
PUTEOLI. Acts xxviii. 13, 14.

Sailing, on the return of spring, in another Alexandrine vessel, of


the same very common name borne by that in which they were
shipwrecked, they came next to Syracuse, on the east side of the
island of Sicily, and after a stay of three days, turned through the
Sicilian strait to Rhegium, on the main-land directly opposite the
island. There Paul first saw the soil of Italy, but did not leave the
vessel for his land journey, till they came, with a fresh south wind, to
Puteoli, a port in the bay of Naples. Here they found Christians, who
invited them to rest among them for a week; after which they
journeyed along the coast, on the noble road of Pozzuoli and Baiae,
for about a hundred miles, to Appius’s Forum, a village about
eighteen miles from Rome. At this place, they were met by a number
of brethren from the church of Rome; and having journeyed along
the Appian way, to the Three Taverns,――a little stopping place a
few miles from the city,――they were received by still another
deputation of Roman Christians, come out to greet the great apostle,
whose name had long been known among them, and whose
counsels and revelations they had already enjoyed by his writings.
This noble testimony of the esteem in which they held him, was a
most joyful assurance to Paul, that, even on this foreign shore, a
stranger and a prisoner, he had many near and dear friends; and his
noble spirit, before probably depressed and melancholy, in the dark
prospect of his approach to the awful seat of that remorseless
imperial power that was to decide his doom, now rose to feelings of
exultation and gratitude. Entering the vast imperial city, the prisoners
were remanded by the centurion to the custody of Burrhus, the noble
and influential praefect of the praetorian guard, who was, ex-officio,
the keeper of all prisoners of state, brought from the provinces to
Rome. Burrhus however, was as kind and accommodating to Paul as
Julius had been, and allowed him to live by himself in a private
house, with only a soldier as an attendant guard.

After three days, Paul invited to his lodgings the chief men of the
Jewish faith, in Rome, and made known to them the circumstances
under which he had been sent thither, and his present relations to
the heads of their religion in Jerusalem. In reply, they merely stated
that they had received no formal communications respecting him,
from Jerusalem, nor had those of their brethren who had arrived
from Judea spoken ill of him. They expressed also a great desire to
hear from him the peculiar doctrine, for entertaining which he had
been thus denounced, of which they professed to know nothing, but
that there was a universal prejudice against it. A day was accordingly
appointed for a full conference on these very important
subjects,――and at the set time, Paul, with no small willingness,
discoursed at great length on his views of the accomplishment of all
the ancient prophecies respecting the Messiah, in the life and death
of Jesus of Nazareth. His hearers were very much divided in opinion
about these points, after his discourse was over,――some believing
and some disbelieving. Leaving them to meditate on what he had
said, Paul dismissed them with a warning quotation from Isaiah,
against their prejudices, and sternly reminded them, that though they
did reject the truth, the waiting Gentiles were prepared to embrace it,
and should receive the word of God immediately. They then left him,
and made his words a subject of much discussion among
themselves; but the results are unrecorded. Paul having hired a
house in Rome, made that city the scene of his active labors for two
whole years, receiving all that called to inquire into religious truth,
and proclaiming the doctrines of Christianity with the most
unhesitating boldness and freedom; and no man in Rome could
molest him in making known his belief to as many as chose to hear
him; for it was not till many years after, that the Christians were
denounced and persecuted by Nero.

his epistles written from rome.

With these facts the noble narrative of Luke ceases entirely, and
henceforth no means are left of ascertaining the events of Paul’s life,
except in those incidental allusions which his subsequent writings
make to his circumstances. Those epistles which are certainly known
and universally agreed to have been written from Rome during this
imprisonment, are those to the Philippians, the Ephesians, the
Colossians, and to Philemon. There are passages in all these which
imply that he was then near the close of his imprisonment, for he
speaks with great confidence of being able to visit them shortly, and
very particularly requests preparation to be made for his
accommodation on his arrival.

There is good reason to think that the epistles to the Ephesians, to


the Colossians, and to Philemon, were written about the same time
and were sent together. This appears from the fact, that Tychicus is
spoken of in both the two former, as sent by the apostle, to make
known to them all his circumstances more fully, and is also implied
as the bearer of both, while Onesimus, the bearer of the latter, is
also mentioned in the epistle to the Colossians as accompanying
Tychicus.

the epistle to the ephesians.

The most important question which has been raised concerning


this epistle, regards the point, whether it was truly directed and sent
by Paul, to the church in Ephesus, as the common reading distinctly
specifies. Many eminent modern critics have maintained that it was
originally sent to the church in Laodicea, and that the word Ephesus,
in the direction and in the first verse, is a change made in later times,
by those who felt interested to claim for this city the honor of an
apostolic epistle. Others incline to the opinion, that it was directed to
no particular church, but was sent as a circular to several churches
in Asia Minor, among which were those of Ephesus and Laodicea,
and that several copies were sent at the same time, each copy being
differently directed. They suppose that when the epistles of Paul
were first collected, that copy which was sent to Ephesus was the
one adopted for this, and that the original manuscript being soon
lost, all written trace of its original general direction disappeared
also.

The prominent reason for this remarkable supposition,


unsupported as it is by the authority of any ancient manuscript, is
that Paul writes apparently with no local reference whatever to the
circumstances of the Ephesians, among whom he had lived for three
years, although his other epistles to places which he had visited are
so full of personal and local matters; and that he speaks on the
contrary as though he knew little of them except by hearsay. A
reference to the particular details of the reasoning by which this
opinion is supported, would altogether transcend the proper limits of
this work; since even a summary of them fills a great many pages of
those critical and exegetical works, to which these discussions
properly belong; and all which can be stated here is the general
result, that a great weight of authority favors the view that this was
probably a circular epistle; but the whole argument in favor of either
notion, rests on so slight a foundation, that it is not worth while to
disturb the common impression for it.

The epistle certainly does not seem to dwell on any local


difficulties, but enlarges eloquently upon general topics, showing the
holy watchfulness of the apostle over the faith of his readers. He
appears, nevertheless, to emphasize with remarkable force, the
doctrines that Christ alone was the source and means of salvation,
“the chief corner-stone,” and that in him all are united, both Jews and
Gentiles, in one holy temple. There is something in many such
passages, with which the epistle abounds, that seems peculiarly well
fitted to the circumstances of mixed communities, made up of Jews
and Gentiles, and as if the apostle wished to prevent the former from
creating any distinctions in the church, in their own favor. Many
passages in this epistle also, are very pointedly opposed to those
heresies, which about that period were beginning to rise up in those
regions, and were afterwards famous under the name of the
Gnosis,――the first distinct sect that is known to have perverted the
purity of Christian truth. Paul here aims with remarkable energy, to
prove that salvation was to be attributed to Christ alone, and not to
the intervention of any other superior beings, by whatever names
they are called, whether principalities, or powers, or might or
dominion, both in this world and the world to come,――in heavenly
places as well as earthly. The apostle also is very full in the moral
and practical part,――urging with great particularity the observance
of those virtues which are the essentials of the Christian character,
and specifying to each particular age, sex, rank and condition, its
own peculiar duties.

the epistle to the colossians.

In the first verse of the second chapter, the apostle expresses a


peculiar anxiety for the spiritual safety of those Christians who have
not seen his face in the flesh, among whom he appears to number
the Colossians and Laodiceans. It seems quite evident that he had
never been at Colosse; for though he traversed Phrygia, on two
several occasions before this time, he is not said to have visited
either Colosse or Laodicea;――but his route is so described, as to
make it almost impossible for him to have taken either city directly in
his way. This circumstance may account for the fact of his
distinguishing in this manner a single city like Colosse, of no great
size or importance; because as it appears from the general tenor of
the epistle, certain peculiar errors had arisen among them, which
were probably more dangerously rife, from the circumstance of their
never having been blessed by the personal presence and labors of
an apostle. The errors which he particularly attacks, seem to be
those of the Judaizers, who were constantly insisting on the
necessity of Mosaical observances, such as circumcision, sabbaths,
abstinence from unclean meats, and other things of the same sort.
He cautions them particularly against certain false doctrines, also
referred to under the names of philosophy, vain deceit, the traditions
of men, &c. which are commonly thought to refer to the errors of the
Essenes, a Jewish sect characterised by Josephus in terms
somewhat similar, and who are supposed to have introduced their
ascetic and mystical doctrines into the Christian church, and to have
formed one of the sources of the great system of Gnosticism, as
afterwards perfected. The moral part of this epistle bears a very
striking similarity, even in words, to the conclusion of that to the
Ephesians,――a resemblance probably attributable in part, to the
circumstance, that they were written about the same time. The
circumstance that he has mentioned to the Colossians an epistle to
be sent for by them from Laodicea, has given rise to a forged
production, purporting to be this very epistle from Paul to the
Laodiceans; but it is manifestly a mere brief rhapsody, collected from
Paul’s other epistles, and has never for a moment imposed upon the
critical. It has been supposed that the true epistle meant by Paul, is
another, now lost, written by Paul to Laodicea; and the supposition is
not unreasonable.

the epistle to philemon.

This was merely a private letter from Paul to a person otherwise


not known, but appearing, from the terms in which he is herein
mentioned, to have been at some time or other associated with Paul
in the gospel work; since he styles him “fellow-laborer.” He appears
to have been a man of some property and generosity, because he
had a house spacious enough to hold a worshiping assembly, who
were freely accommodated by him; and he is likewise mentioned as
hospitably entertaining traveling Christians. The possession of some
wealth is also implied in the circumstance which is the occasion of
this epistle. Like almost all Christians of that age who were able to
do so, he owned at least one slave, by name Onesimus, who had
run away from him to Rome, and there falling under the notice of
Paul, was made the subject of his personal attentions, and was at
last converted by him to the Christian faith. Paul now sends him back
to his old master, with this letter, in which he narrates the
circumstances connected with the flight and conversion of
Onesimus, and then with great earnestness, yet with mildness,
entreats Philemon to receive him now, not as a slave, but as a
brother,――to forgive him his offenses, and restore him to favor.
Paul himself offers to become personally responsible for all
pecuniary loss experienced by Philemon in consequence of the
absence of his servant in Rome, where he had been ministering to
Paul; and the apostle gives ♦ his own note of hand for any
reasonable amount which Philemon may choose to claim.
Throughout the whole, he speaks in great confidence of the ready
compliance of Philemon with these requests, and evidently considers
him a most intimate friend, loving and beloved. He also speaks with
great confidence of his own speedy release from his bonds, and
begs Philemon to prepare him a lodging; for he trusts that through
his prayers, he shall shortly be given to him.

♦ duplicate word “his” removed

the epistle to the philippians.

That this was written after the others that were sent from Rome by
Paul during this imprisonment, is proved by several circumstances.
Luke was certainly with him when he wrote to the Colossians and to
Philemon; but no mention whatever is made of him in the epistle to
the Philippians, who would, nevertheless, feel as much interest in
him as in Timothy or any companion of Paul; because he had
resided in Philippi many years, and must have had many
acquaintances there, who would expect some account of him, and
some salutation from him. Paul, moreover, says, that he trusts to
send Timothy shortly to them, because he has no man with him who
is like minded, or who will care for their state;――a remark which, if
Luke had been with him, he could not have made with any justice to
that faithful and diligent associate, who was himself a personal
acquaintance of the Philippians. There were some circumstances
connected with the situation of Paul, as referred to in this epistle,
which seem to imply a different date from those epistles just
mentioned. His condition seems improved in many respects,
although before not uncomfortable, and his expectations of release
still more confident, though before so strong. He speaks also of a
new and remarkable field in which his preaching had been
successful, and that is, the palace of the imperial Caesar himself,
among whose household attendants were many now numbered
among the saints who sent salutations to Philippi. The terms in which
he mentions his approaching release, are still more remarkable than
those in the former epistles. He says――“Having this confidence, I
know that I shall abide and continue with you all,” &c. “that your
rejoicing may be more abundant, by my coming to you again.” “I trust
in the Lord that I shall myself also come shortly.”

The immediate occasion of this epistle was the return of


Epaphroditus, the apostle or messenger of the Philippian church, by
whom Paul now wrote this, as a grateful acknowledgment of their
generosity in contributing to his support that money, of which
Epaphroditus was the bearer. In the epistle, he also took occasion,
after giving them an account of his life in Rome, to warn them
against the errors of the Judaizers, whose doctrines were the
occasion of so much difficulty in the Christian churches.

the epistle to the hebrews.

The release which Paul so confidently anticipated, probably


happened shortly after the writing of the last epistle, and at this time,
just before leaving Italy for another field of labor, it is commonly
believed that he wrote his epistle to the Hebrews. Of the particular
place, the time, the immediate object, and the persons who were the
receivers of this epistle, nothing is with any certainty known; and the
whole range of statements in standard works of exegetical and
critical theology, on this writing, is the most appalling mass of vague
speculations, unfounded conclusions and contradictory assertions,
that presents itself to the historian of the apostolic works in any
direction; and in respect to all these points, referring the critical to
any or all of the thousand and one views, given in the learned and
elaborate introductions and commentaries, which alone can with any
justice so much as open the subject, the author excuses himself
entirely from any discussion of this endless question, in the words
used on one of these points, by one of the most learned, acute,
ingenious and cautious critics of modern times. “Any thing further on
this subject I am unable to determine, and candidly confess my
ignorance as to the place where the epistle to the Hebrews was
written. Nor do I envy any man who pretends to know more on this
subject, unless he has discovered sources of intelligence, which
have hitherto remained unknown. It is better to leave a question in a
state of uncertainty, than, without foundation, to adopt an opinion
which may lead to material errors.”

voyage to the east.

On leaving Italy after this release, he seems to have directed his


course eastward; but nothing whatever is known of his motions,
except that from the epistle of Titus it is learned that he journeyed to
Miletus, to Ephesus, to Troas, to Macedonia, to Crete and to
Epirus,――and last of all, probably, to Rome. His first movements on
his release were, doubtless, in conformity with his previous designs,
as expressed in his epistles. He probably went first to Asia, visiting
Ephesus, Miletus, Colosse, &c. On this voyage he might have left
Titus in Crete, (as specified in his letter to that minister,) and on
embarking for Macedonia, left Timothy at Ephesus, (as mentioned in
the first epistle to him.) After visiting Philippi and other places in
Macedonia, where he wrote to Timothy, he seems to have crossed
over the country to the shore of the Ionian sea, to Nicopolis, whence
he wrote to Titus, to come from Crete, and join him there. These two
epistles, being of a merely personal character, containing
instructions for the exercise of the apostolic functions of ordination,
&c. in the absence of Paul, can not need any particular historical
notice, being so simple in their object that they sufficiently explain
themselves. Respecting that to Timothy, however, it may be specified
that some of its peculiar expressions seem to be aimed at the rising
heresy of the Jewish and Oriental mystics, who were then infecting
the eastern churches with the first beginnings of that heresy which,
under the name of the Gnosis, or science, (falsely so called,) soon
after corrupted with its dogmas, a vast number in Asia Minor, Greece
and Syria. The style and tenor of both of the epistles are so different
from all Paul’s other writings, as to make it very evident that they
were written at a different time, and under very different
circumstances from the rest.

return to rome.

The only real evidence of this movement of Paul is found in the


tenor of certain passages in the second epistle to Timothy, which
seem to show that it was written during the author’s imprisonment in
Rome, but which cannot be connected with his former confinement
there. In the former epistles written from Rome, Timothy was with
Paul;――but this of course implies that he was absent. In them,
Demas is declared to be with Paul;――in this he is mentioned as
having forsaken him, and gone to Thessalonica. In the first epistle to
Timothy, Mark was also with Paul, and joined in saluting the
Colossians; in this, Timothy is instructed to bring him to Paul,
because he is profitable to him in the ministry. In the fourth chapter,
Paul says that “Erastus abode at Corinth;”――an expression which
implies that Erastus abode in Corinth when Paul left it. But Paul took
no journey from Corinth before his first imprisonment; for when he
left that place for the last time before his journey to
Jerusalem,――when he was seized and sent to Rome,――he was
accompanied by Timothy; and there could therefore be no need of
informing him of that fact. In the same passage of this epistle he also
says, that he had left Trophimus sick at Miletus; but when Paul
passed through Miletus, on that journey to Jerusalem, Trophimus
certainly was not left behind at Miletus, but accompanied him to
Jerusalem; for he was seen there with him by the Asian Jews. These
two passages therefore, refer to a journey taken subsequent to
Paul’s first imprisonment,――and the epistle which refers to them,
and purports in other passages to have been written during an
imprisonment in Rome, shows that he returned thither after his first
imprisonment.

The most striking passage in this epistle also refers with great
distinctness to his expectation of being very speedily removed from
apostolic labors to an eternal apostolic reward. “I am now ready to
be offered, and the time of my departure is at hand. I have fought the
good fight; I have finished my course; I have kept the faith:
henceforth, there is laid up for me a crown of life, which the Lord, the
righteous judge, shall give me at that day.” All these expressions are
utterly at variance with those hopes of release and of the speedy
renewal of his labors in an eastern field; and show very plainly that
all the tasks to which he once looked forward were now completed,
and that he could hope for no deliverance, but that which should call
him from chains and toils to an eternal crown.

his death.

The circumstance of his being again in Rome a prisoner, after


having been once set free by the mandate of the emperor himself,
after a full hearing, must at once require a reference to a state of
things, in which Paul’s religious profession and evangelizing labors,
before esteemed so blameless that no man in Rome forbade him to
preach the gospel there,――had now, by a mighty revolution in
opinions, become a crime, since for these, he was now held in
bondage, without the possibility of escape from the threatened
death. Such a change actually did occur in the latter part of the reign
of Nero, when, as already related in the history of Peter’s first epistle,
the whole power of the imperial government was turned against the
Christians, as a sect, and they were convicted on that accusation
alone, as deserving of death. The date of this revolution in the
condition of the Christians, is fixed by Roman history in the sixty-
fourth year of Christ; and the time when Paul was cast into chains
the second time, must therefore be referred to this year. His actual
death evidently did not take place at once, but was deferred long
enough to allow of his writing to Timothy, and for him to make some
arrangements therein, for a short continuance of his labors. The date
which is commonly fixed as the time of his execution, is in the year of
Christ 65; but in truth, nothing whatever is known about it, nor can
even a probability be confidently affirmed on the subject. Being a
Roman citizen, he could not die by a mode so infamous as that of
the cross, but was beheaded, as a more honorable exit; and with this
view, the testimony of most of the early Fathers, who particularize his
death, distinctly accords.

Of the various fictions which the monkish story-tellers have invented to gratify the
curiosity which Christian readers feel about other particulars of the apostle’s character, the
following is an amusing specimen. “Paul, if we may believe Nicephorus, was of a low and
small stature, somewhat stooping; his complexion fair; his countenance grave; his head
small; his eyes sparkling; his nose high and bending; and his hair thick and dark, but mixed
with gray. His constitution was weak, and often subject to distempers; but his mind was
strong, and endued with a solid judgment, quick invention, and prompt memory, which were
all improved by art, and the advantages of a liberal education. Besides the epistles which
are owned to be genuine, several other writings are falsely ascribed to him: as an epistle to
the Laodiceans, a third to the Thessalonians, a third to the Corinthians, a second to the
Ephesians, his letter to Seneca, his Acts, his Revelation, his voyage to Thecla, and his
Sermons.” (Cave’s Lives of the Apostles.)

But the honors and saintship of Paul are recorded, not in the
vague and misty traces of bloody martyr-death, but in the far more
glorious achievements of a heroic life. In these, are contained the
essence of his greatness; to these, all the Gentile world owes its
salvation; and on these, the modern historian, following the model of
the sacred writers, dwells with far more minuteness and particularity,
than on a dull mass of uncertain tradition.
JOSEPH BARNABAS.
Of this apostle, so few circumstances are known, that are not
inseparably connected with the life of Paul, in which they have been
already recorded, that only a very brief space can be occupied with
the events of his distinct life. The first passage in which he is
mentioned, is that in the fourth chapter of Acts, where he is specified
as having distinguished himself among those who sold their lands,
for the sake of appropriating the avails to the support of the Christian
community. Introduced to the notice of the reader under these most
honorable circumstances, he is there described as of the tribe of
Levi, and yet a resident in the island of Cyprus, where he seems to
have held the land which he sacrificed to the purposes of religious
charity. This island was for a long time, before and after that period,
inhabited by great numbers of wealthy Jews, and there was hardly
any part of the world, where they were so powerful and so favored,
as in Cyprus; so that even the sacred order of the Levites might well
find inducements to leave that consecrated soil to which they were
more especially attached by the peculiar ordinances of the Mosaic
institutions, and seek on this beautiful and fertile island, a new home,
and a new seat for the faith of their fathers. The occasion on which
Joseph (for that was his original name) left Cyprus to visit Jerusalem,
is not known; nor can it even be determined whether he was ever
himself a personal hearer of Jesus. He may very possibly have been
one of the foreign Jews present at the Pentecost, and may there
have been first converted to the Christian faith. On his distinguishing
himself among his new brethren, both by good words and generous
deeds, he was honored by the apostles with the name of Barnabas,
which is interpreted in Greek by words that may mean either “son of
consolation,” or “son of exhortation.” The former sense, of course,
would aptly refer to his generosity in comforting the poor apostolic
community, by his pecuniary contributions, as just before mentioned;
and this has induced many to prefer that meaning; but the majority of
critical translators and commentators have been led, on a careful
investigation both of the original Hebrew word and of the Greek
translation of it, to prefer the meaning of “son of exhortation” or
“instruction,” a meaning which certainly well accords with the
subsequent distinction attained by him in his apostolic labors. Both
senses may, however, have been referred to, with an intentional
equivoque.

“Acts, chapter iv. verse 37. ὑπάρχοντος αὐτῳ ἀγροῦ He could not have sold that which was
his paternal inheritance as a Levite; but this might perhaps be some legacy, or purchase of
land in Judea, to which he might have a title till the next jubilee, or perhaps some land in
Cyprus. (Doddridge.) That it was lawful for the Levites to buy land, we learn from the
example of Jeremiah himself, who was of the tribe of Levi. See Jeremiah xxxii. 17. It is
observed by Bp. Pearce, that those commentators who contend that this land must have
belonged to his wife, because, according to the law mentioned in Numbers xviii. 20, 23 and
24, a Levite could have no inheritance in Israel, seem to have mistaken the sense of that
law, ‘which,’ says he, ‘means only that the Levites, as a tribe, were not to have a share in
the division of Canaan among the other tribes. This did not hinder any Levite from
possessing lands in Judea, either by purchase or by gift, as well as in right of his wife.
Josephus was a Levite, and a priest too; and yet in his Life, chapter 76, he speaks of lands
which he had lying about Jerusalem, and in exchange of which, Vespasian gave him others,
for his greater benefit and advantage. After all, I see no reason why we may not suppose
that this land, which Barnabas had and sold, was not land in Judea; and if so, the words of
the law, “no inheritance in Israel,” did not, however understood, affect their case. His land
might have been in his own country, Cyprus, an island of no great distance from Judea; and
he might have sold it at Jerusalem to some purchaser there; perhaps to one of his own
countrymen.’” (Bloomfield’s Annotations, Vol. IV. pp. 147, 148.)

In all the other passages of the New Testament in which he is


mentioned, he is associated with Paul, and every recorded act of his
life has been already given in the life of his great associate. His first
acquaintance with him on his return to Jerusalem after his
conversion,――his mission to Antioch and labors there in
conjunction with Paul, when he had brought him from
Tarsus,――their visit to Jerusalem,――their return to
Antioch,――their first great mission through Asia Minor――their visit
to Jerusalem at the council, and their joint report,――their second
return to Antioch,――their proposed association in a new
mission,――their quarrel and separation,――have all been fully
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