Chapter6 The Basics of
JavaScript
• 6.1 Overview of JavaScript
• 6.2 Object Orientation and JavaScript
• 6.3 General Syntactic Characteristics
• 6.4 Primitives, Operations, and
Expressions
• 6.5 Screen Output
• 6.6 Control Statements
• 6.7 Object Creation and Modification
• 6.8 Arrays

 

©

Chapter6 The Basics of
JavaScript
• 6.9 Functions
• 6.10 An Example
• 6.11 Constructors
• 6.12 Pattern Matching
• 6.13 Another Example
• 6.14 Summary
• 6.15 Review Questions
• 6.16 Exercises

 

©

Chapter6 The Basics of
JavaScript
• JavaScript is sometimes divided into three
parts, called the core, cent side, and
server side.
• The core is the heart of the language,
including its operators, expressions,
statements, and subprograms.

 

©

Chapter6 The Basics of
JavaScript
• Cent-side JavaScript is a collection of objects
that support control of the browser and
interactions with users. For example, with
JavaScript, and HTML document can be made
to be responsive to user inputs such as mouse
ccks and form submissions.
• Server-side JavaScript is a collection of objects
that make the language useful on a Web server,
for example, to support communication with a
database management system.

 

©

Chapter6 The Basics of
JavaScript
• This chapter takes you on a quick tour of core
JavaScript, introducing its most important
concepts and constructs but leaving out some of
the details of the language. In spite of this
chapter’s brevity, however, if you are an
experienced programmer you should be able to
learn how to be an effective JavaScript
programmer by studying this chapter (and
Chapter 7, “JavaScript and HTML Documents, ”
which discusses cent-side JavaScript, focusing
on events, event handng, and ways to deal with
HTML forms in JavaScript). If you want more
details, you can find numerous books devoted
solely to JavaScript.

 

©

Chapter6 The Basics of
JavaScript
• Server-side JavaScript is used far less
frequently than cent-side JavaScript.
Because of this, this book does not cover
server-side JavaScript.

 

©

6.1 Overview of JavaScript
• This section discusses the origins of
JavaScript, a few of its characteristics, and
some of its uses. Included are a
comparison of JavaScript and Java and a
brief introduction to event-driven
programming.

 

©

6.1.1 ORIGINS
• JavaScript, which was originally named
veScript, was developed by Netscape.
• In late 1995, veScript became a joint
venture of Netscape and Sun
Microsystems, and its name was changed
to JavaScript.

 

©

6.1.1 ORIGINS
• JavaScript has gone through extensive evolution,
moving from version 1.0 to version 1.4 by adding
many new features.
• A language standard for JavaScript has been
developed by the European computer
manufacturers Association (ECMA) as ECMA-
262. This standard has also been approved by
the International Standards Organization (ISO)
as ISO 16262. The standard specification can be
found at ww.ecma.ch.
• All currently available implementations of
JavaScript are based on this standard, although
not all include all of its constructs.

 

©

6.1.2 PROGRAMS OR
SCRIPTS
• In Chapter 4, “The Basics of Perl,” we
referred to Perl code collections as
programs, although others refer to them as
scripts.
• However, we prefer the term script for
JavaScript, mainly because JavaScript
code can be scattered in various parts of
an HTML document.

 

©

6.1.2 PROGRAMS OR
SCRIPTS
• Which part would be a program ? or ,
would it be a collection a programs? to
avoid this issue, we always refer to every
collection of JavaScript code as a script.
• An HTML document can include any
number of embedded scripts.

 

©

6.1.3 JAVASCRIPT AND
JAVA
• Although JavaScript’s name appears to
connote a close relationship with Java,
JavaScript and Java are actually very
different. One difference is support for
object-oriented programming.
• Although JavaScript is often described as
being an object-oriented language, its
object model is quite different from that of
Java and C++, As you shall see in Section
6.2 “Object Orientation and JavaScript.”

 

©

6.1.3 JAVASCRIPT AND
JAVA
• In fact , JavaScript does not support the
object-oriented software development
paradigm. Although it has objects, it does
not have classes and does not support
inheritance.
• Java, on the other hand, provides
complete support for object-oriented
programming.

 

©

6.1.3 JAVASCRIPT AND
JAVA
• Java is a strongly typed language. Types
are all known at compile time and are
checked for compatibity.
• Variables in JavaScript is that objects in
Java are static in the sense that their
collection of data an methods is fixed at
compile time.

 

©

6.1.3 JAVASCRIPT AND
JAVA
• JavaScript objects are dynamic-the
number of data members and methods
can change during execution.
• The main similarity between Java and
JavaScript is syntax of its expressions,
assignment statements, and control
statements.

 

©

6.1.4 USE OF JAVASCRIPT
• The original goal of JavaScript was to
provide programming capabity at both the
server and cent ends of a Web
connection. Since then, JavaScript has
grown into a full-fledged programming
language that can be used for a variety of
appcation areas. In this book, we focus
on uses of JavaScript for the cent side of
Web programming.

 

©

6.1.4 USE OF JAVASCRIPT
• First, cent-side JavaScript can serve as
an alternative for much of what is done
with CGI programming, in which
computational capabity resides on the
server and is requested by the cent.
• On the other hand, is embedded in HTML
documents and is interpreted by the
browser.

 

©

6.1.4 USE OF JAVASCRIPT
• JavaScript cannot replace all of CGI
computing. In particular, while CGI Perl
supports file operations and networking,
JavaScript supports neither.
• JavaScript is often used as an alternative
to Java applets.
• Java applets are downloaded separately
from the HTML documents that call them;

 

©

6.1.4 USE OF JAVASCRIPT
• Interactions with users through form
elements, such as buttons and menus, are
easy to describe in JavaScript. Because
events, such as button ccks, are easily
detected with JavaScript, they can be
used to trigger computations and provide
feedback to the user.

 

©

6.1.4 USE OF JAVASCRIPT
• Perhaps the most exciting capabity of
JavaScript has been make possible by the
development of access and modify the
controls and content of any element of
displayed HTML document, making
formally static documents highly dynamic.

 

©

6.1.5 EVERNT-DRIVEN
COMPUTATION
• Much of what JavaScript scripts do is eventdriven,
meaning that the actions are executed in
response to actions of the users of documents,
among them mouse ccks and form submissions.
• One of the common uses of JavaScript is to
check the values provided in forms to determine
whether they are sensible.
• The CGI Program that processes the form data
must find input errors and transmit that
information back to the browser, which then asks
the user to resubmit alternative input.

 

©

6.1.6 BROWSERS AND
HTML/JAVASCRIPT DOCUMENTS
• As discussed earer, JavaScript is
embedded in HTML documents. If the
HTML document does not include
embedded scripts, the browser reads the
nes of the document and renders its
window according to the tags, attributes,
and tag content it finds and recognizes.

 

©

6.1.6 BROWSERS AND
HTML/JAVASCRIPT DOCUMENTS
• When a JavaScript is encountered in the
document, the browser uses its JavaScript
interpreter to deal with the script. After that,
the browser goes back to reading HTML
and rendering its window.
• The two parts of an HTML document, the
head an the body, have distinct purposes.
JavaScript scripts can appear in either part
of a document, depending on their
purpose.

 

©

6.1.6 BROWSERS AND
HTML/JAVASCRIPT DOCUMENTS
• Scripts that produce content on demand or
that react to user interactions are placed in
the head of the document. Generally, this
means function definitions and code
associated with form elements, such as
buttons.

 

©

6.1.6 BROWSERS AND
HTML/JAVASCRIPT DOCUMENTS
• On the other hand, scripts that are to be
interpreted just once, when the interpreter finds
them, are placed in the document body.
• Accordingly, the interpreter notes the existence
of scripts that appear in the head of a document,
but it does not interpret them while going
through the head. Scripts that are found in the
body of a document are interpreted as they are
found.

 

©

6.2 Object Orientation and
JavaScript
• JavaScript does not have classes. Its
objects serve both as objects and as
models of objects.
• It does support a technique that can be
used to simulate some of the aspects of
inheritance. This is done with the
prototype object-thus, this form of
inheritance is called prototype-based
inheritance.

 

©

6.2 Object Orientation and
JavaScript
• Without class-based inheritance, JavaScript
cannot support polymorphism. A polymorphic
variable can reference related objects of
different classes within the same class hierarchy.
A method call through such a polymorphic
variable can be dynamically bound to the
method in the object ’s class.
• Despite the fact that JavaScript is not an objectoriented
language, much of its design is rooted
in the approaches used in object-oriented
programming. Cent-side JavaScript deals in
large part with documents and document
elements, with it treats as objects.

 

©

6.2.1 JAVASCRIPT
OBJECTS
• In JavaScript, objects have collections of
properties. Each property is either a data
property or a method property.
• Data properties appear in two categories:
– primitive values
– references to the other objects
• Sometimes we will refer to the data
properties simply as properties; We often
refer to the method properties simply as
methods.

 

©

6.2.1 JAVASCRIPT
OBJECTS
• JavaScript uses non-object types for some
of its simplest data types--these types are
called the primitives of the language.
• Primitives are used because they often
can be implemented directly in hardware,
resulting in faster operations on their
values.
• Primitives are exactly ke the simple
scalar variables of non-object-oriented
languages.

 

©

6.2.1 JAVASCRIPT
OBJECTS
• All objects in a JavaScript program are
indirectly accessed through variables.
• All primitive values in JavaScript are
accessed directly. The properties of an
object are referenced by attaching the
name of the property to the variable that
references the object.
myCar.engine.

 

©

6.2.1 JAVASCRIPT
OBJECTS
• Each object is a st of property-value pairs. The
properties are names; the values are data
values or functions.
• All functions are objects and are referenced
through variables.
• The collection of properties of a JavaScript
object is dynamic-properties can be added or
deleted at any time.
• Every object is characterized by its collection of
properties, although objects do not have types in
any formal sense.

 

©

6.3 General Syntactic
Characteristics
• In this book, all JavaScript scripts are embedded
in HTML documents.
• The most common situation is that the script
appears as the content of a <script> tag.
• Another common way to specify a JavaScript
script in an HTML document is with the src
attribute of <script> tag, whose value is the
name of a file that contains the script
<Script language=“JavaScript”
src=“tst_number.js”> </script>

 

©

6.3 General Syntactic
Characteristics
• Identifiers, or names, in JavaScript are similar to
those of other common programming languages.
The must begin with a letter, an underscore (_),
or a dollar sign ($). (Dollar signs are not
intended to be used by user-written scripts,
although that is legal.)
• Subsequent characters may be letters,
underscores, dollar signs, or digits.
• There is no length mitation for identifiers.
• The letters in variable name are case-sensitive.

 

©

6.3 General Syntactic
Characteristics
• JavaScript has 25 reserved words, which
are sted in Table 6.1.
default for new try with
continue finally instanceof throw while
catch else in this void
case do if switch var
break delete function return typeof

 

©

6.3 General Syntactic
Characteristics
• With JavaScript, there are two forms of
comments, both of which are used in other
languages.
– First, whenever two adjacent slashes (//)
appear on a ne, the rest of the ne is
considered a comment.
– Second, both single- and multiple-ne
comments can be written using / * to introduce
the comment and */ to terminate it.

 

©

6.3 General Syntactic
Characteristics
• Scripts are sometimes hidden form non-
JavaScript browsers by putting them in HTML
comments. The HTML comment introduction (<!-
-) works fine as a hiding prelude to JavaScript
code.
• However, the syntax for closing a comment that
encloses JavaScript code must be special. It is
the usual HTML comment closer, but it must be
on its own ne and must be preceded by two
slashes.
<!--
--JavaScript script--
//-->

 

©

6.4 Primitives, Operations,
and Expressions
• The primitive data types, operations, and
expressions of JavaScript are similar to
those of other common programming
languages.

 

©

6.4.1 PRIMITIVE TYPES
• JavaScript have five primitive types
– Number
– String
– Boolean
– Undefined
– Null
• JavaScript includes predefined objects that are
closely related to the Number, String, and
Boolean types, named Number, string, and
Boolean. These three objects are called wrapper
objects

 

©

6.4.1 PRIMITIVE TYPES
• They contain a property to store the value of
their corresponding primitive types.
• Their use of the primitive types. In the case of
Number, the properties are more useful; in the
case of String, the methods are more useful.
• Because JavaScript coerces values between the
Number and String types and the Number and
String objects, respectively, the methods of
these two objects can be used on variables of
the corresponding primitive types.
• In most case you can simply treat Number and
String type values as if they ware objects.

 

©

6.4.1 PRIMITIVE TYPES
• The difference between primitives and
objects is illustrated in the following
example.
17 17
Non-heap Memory
prim
obj
a primitive an object

 

©

6.4.2 NUMERIC AND
STRING TERALS
• All number terals are values of type
Number.
• The numeric values of JavaScript are
represented in double-precision floatingpoint
form.
• teral numbers forms in a script
72 7.2 .72 72. 7E2 7e2 .7e2 7.e2 7.2E-2

 

©

6.4.2 NUMERIC AND
STRING TERALS
• Integer terals can be written in
hexadecimal form by preceding their first
digit with either 0x or 0X.
• A string teral is a sequence of zero or
more characters demited by either single
quotes (‘) or double quotes (“). String
terals can include characters specified
with escape sequences, such as /n. and /t.

 

©

6.4.2 NUMERIC AND
STRING TERALS
• If you want an actual single-quote
character in a string teral that is demited
by single quotes, the embedded single
quote is preceded by backslash:
‘You/’re the most freckly person I/ ’ve ever met’
• A double quote can be embedded in a
double-quoted string teral by preceding it
with a backslash.
“D://bookfiles”

 

©

6.4.2 NUMERIC AND
STRING TERALS
• There is no difference between singlequoted
and double quoted teral strings.
• The null string can be denoted with either ‘’
or “”.
• All string terals are primitive values.

 

©

6.4.3 OTHER PRIMITIVE
TYPES
• The only values of type Boolean are true
and false.
• The only values of type Null is Null, which
can be either a primitive value or an object.
The null value is a particular value that an
object reference variable has when it does
not refer to any object. When interpreted
as primitive Boolean value, null is false; as
a number, it is 0.

 

©

6.4.3 OTHER PRIMITIVE
TYPES
• The only value of type Undefined is
undefined, which is used as the value of a
variable that has not been assigned a
value. undefined is often used to
determine whether a variable has been
assigned a value. If used as a Boolean,
undefined is interpreted as false; when
used as a number, it is interpreted as NaN
(See section 6.4.7 “The Number Object”)

 

©

6.4.4 DECLARING
VARIABLES
• One of the characteristics of JavaScript
that sets it apart from other common
programming language is that it is
dynamically typed.
• This means that a variable can be used for
anything. It can have the value of any
primitive type, or can be a reference to any
object.

 

©

6.4.4 DECLARING
VARIABLES
• The type of a particular appearance of a variable
in a program is determined by the interpreter. In
many cases, the interpreter converts the type of
the value of a variable to whatever is needed for
the context in which it appears.
• A variable can be declared either by assigning it
a value, in which case the interpreter impcitly
declares it to be a variable, or by sting it on a
declaration statement, which begins with the
reserved word var.

 

©

6.4.4 DECLARING
VARIABLES
• Initial values can t included in a var
declaration, as with some of the variables
in the following declaration:
var counter,
index,
pi = 3.14159265,
quarterback = "Elway",
stop_flag = true;

 

©

6.4.5 NUMERIC
OPERATORS
• JavaScript has the typical collection of numeric operators.
These are the binary operators
– + for addition
– - for subtraction
– * for multipcation
– / for division and % for modulus.
• The unary operators are
– negate (-),
– decrement (- -),
– increment (++).
– The increment and decrement operators can be either prefix
postfix.
• (++a) * 3
• (a++) * 3

 

©

6.4.5 NUMERIC
OPERATORS
• All numeric operations are done in doubleprecision
floating point.
• The precedence rules of a language specify
which operator is evaluated first when two
operators with different precedence are adjacent
in an expression. Adjacent operators are
separated by a single operand.
• the precedence and associabity of the numeric
operators of JavaScript are given in Table 6.2.

 

©

6.4.6 THE Math OBJECT
• The Math object provides a collection of
properties and methods that operate on Number
objects. The Math object has methods for the
trigonometric functions, such as sin (for sine)
and cos (for cosine), as well as for other
commonly used mathematical operations.
Among these are floor, to truncate a number;
• round, to round a number; and max, to return
the largest of two given numbers. The floor and
round methods are used in the example script in
Section 6.10 “An Example."

 

©

6.4.7 THE Number OBJECT
• The Number object includes a collection of
useful properties that have constant
values. The properties of Number are
shown in Table 6.3.
• These properties are referenced through
Number—for example:
Number. MIN_VALUE

 

©

6.4.7 THE Number OBJECT
• Any arithmetic operation that results in an error,
such as division by zero, OS a value that cannot
be represented as a number, such as one that
results in overflow, returns the value not a
number, which is displayed as NaN. If NaN is
compared for equaty against any number, the
comparison fails.
• In fact, in a comparison, NaN is not equal to
itself. To determine whether a variable has the
NaN value, the predefined predicate function is
NaN () must be used.
• For example, if the variable a has the NaN value,
is NaN (a) returns true.

 

©

6.4.7 THE Number OBJECT
• The Number object has a method, toString,
that converts the number through which it
is called to a string. Because numeric
primitives and Number objects are always
coerced to the other when necessary,
toString can be called through a numeric
primitive—for example:
var price = 427, str_price;
str_price = price.toString();

 

©

6.4.8 THE STRING
CATENATION OPERATOR
• JavaScript strings are not stored or treated
as arrays of characters; rather, they are
unit scalar values. String catenation is
specified with the operator denoted by a
plus sign (+). For example, if the value of
first is " Freddie ", the value of this
expression is " Freddie Free loader ":
first + " Freeloader"

 

©

6.4.9 IMPCIT TYPE
CONVERSIONS
• JavaScript includes several different
impcit type conversions. In general, when
a value of one type is used in a situation
that requires a value of a different type,
JavaScript attempts to convert the value to
the type that is required.
• The most common examples of these
conversions involve primitive string and
number values.

 

©

6.4.9 IMPCIT TYPE
CONVERSIONS
• If one of the operands of the catenation operator
is a string and the other is of some other type,
the non string is converted to a string, as in this
example:
"August " + 1977 evaluates to
"August 1997“
• In fact, if either operand of the catenation
operator is a string, the other is converted to a
string. So, in the following expression, the first
operand is converted to a string:
1977 + "August"

 

©

6.4.9 IMPCIT TYPE
CONVERSIONS
• Now consider the expression:
7 * " 3"
• In this expression, the operator is only used with
numbers. This forces numeric context on the
right operand. So JavaScript attempts to convert
it to a number. In this example, the conversion
succeeds and the value of this expression is 21.
• If the second operand were a string that could
not be converted to a number, such as "August",
the conversion would produce NaN, which would
be the value of the expression.

 

©

6.4.9 IMPCIT TYPE
CONVERSIONS
• As we shall see in Section 6.6.1,"Control
Expressions," the relational operators also
cause impcit type conversions.

 

©

6.4.10 String PROPERTIES
AND METHODS
• Because JavaScript coerces primitive
string values to and from String objects
when necessary, the difference between
the String object and the String type does
not affect us. String methods can always
be used through String primitive values, as
if the values were objects. The String
object includes one property, length, and a
large collection of methods.

 

©

6.4.10 String PROPERTIES
AND METHODS
• The number of characters in a string is
stored in the length property:
var sir = "George";
var len = sir.length;

 

©

6.4.10 String PROPERTIES
AND METHODS
• A few of the most commonly used String
methods are shown in Table 6.4.

 

©

6.4.10 String PROPERTIES
AND METHODS
• For example, if you have this ne
var str = "George";
then the following expressions have the shown
values:
str.charAt(2) is 'o'
str.indexOf('r') is 3
str.substring(2, 4) is 'or'
str.toLowerCase() is 'george‘
• Several String methods associated with pattern
matching are described in Section 6.1.2,
"Programs or Scripts."

 

©

6.4.10 String PROPERTIES
AND METHODS
• JavaScript has two predefined functions that are
often useful. These two, parseInt and parseFloat,
are not String methods, so they are not called
through String objects. However, they operate
on the strings given as their parameters. The
parseInt function searches the string for an
integer value. If one is found at the beginning of
the string, it is converted to a number and
returned. If the string does not begin with a vad
integer, NaN is returned. The parseFloat
function is similar to parseInt, but it searches for
a floating-point constant, which could have a
decimal point or an exponent.

 

©

6.4.10 String PROPERTIES
AND METHODS
• Because of the kinds of coercions
JavaScript normally does, as discussed in
Section 6.4.9, "String Properties and
Methods," parseInt and parseFloat are not
often needed.

 

©

6.4.11 THE
typeof
OPERATOR
• The typeof operator returns the type of its single
operand. This is quite useful in some
circumstances in a script, typeof evaluates to
"number", " string ", or " boolean "
• if the operand is of primitive type Number, String,
or Boolean, respectively.
• If the operand is an object or null, typeof
evaluates to "object ".This illustrates a
fundamental characteristic of JavaScript —
objects do not have types.

 

©

6.4.11 THE
typeof
OPERATOR
• Notice that the typeof operator always
returns a string.
• The operand for typeof can be placed in
parentheses, making it appear to be a
function.
• For example, typeof x and typeof (x) are
equivalent.

 

©

6.4.12 ASSIGNMENT
STATEMENTS
• The assignment statement in JavaScript is
exactly as the assignment statement in Perl, as
well as that of other common programming
languages. There is a simple assignment
operator, denoted by =, and a host of compound
assignment operators, such as += and /=. For
example, this statement
a += 7;
means the same as this one:
a = a + 7;

 

©

6.5 Screen Output
• A JavaScript script is interpreted while the
browser interprets the body of the HTML
document in which the script is found. So,
the normal output screen for JavaScript is
the same as the screen in which the
content of the host HTML is displayed.
JavaScript models the HTML document
with the Document object. The window in
which the browser displays an HTML
document is modeled with the Window
object.

 

©

6.5 Screen Output
• The Window object includes two
properties, document and window.
– The document property refers to the
Document object;
– the window property refers to its object.
Window.

 

©

6.5 Screen Output
• The document object has several properties and
methods. The most interesting and useful of its
methods, at least for now, is write, which is used
to dynamically create HTML document content,
which serves as script output. This content is
specified in the parameter to write. For example,
the following produces the screen shown in
Figure 6.2:
document.write("Hello from your JavaScript interpreter");

 

©

6.5 Screen Output
• Because write creates HTML code, the
only useful punctuation in its parameter is
in the form of HTML tags. Therefore, the
parameter to write sometimes includes
<br/>, but never /n.

 

©

6.5 Screen Output
• The parameter to write can include any
HTML tags and content. The parameter is
simply handed to the browser, which treats
it exactly as any other part of the HTML
document. If the parameter to write
consists of several strings separated by
commas, they are catenated together.

 

©

6.5 Screen Output
• As stated previously, the Window object is
the JavaScript model for the browser
window. Window includes three methods
that create dialog boxes for specific kinds
of user interactions. The default object for
JavaScript is the Window object currently
being displayed, so calls to these methods
need not include an object reference.

 

©

6.5 Screen Output
• The alert
method opens a dialog window and
displays its parameter in that window. It also
displays a button labeled OK. The parameter
string to alert is not HTML code; it is plain text.
Therefore, the string parameter to alert may
include /n, but never < br/>. As an example of an
alert, consider this code, which produces the
dialog box shown in Figure 6.3.
alert("Hello from your JavaScript interpreter /n");

 

©

6.5 Screen Output
• The confirm
method opens a dialog window in
which it displays its string parameter, along with
two buttons, OK and Cancel, confirm returns a
Boolean value that indicates the user's button
input, true for OK and false for Cancel.
• This method is often used to offer the user the
choice of continuing some process. For example,
this produces the screen shown in Figure 6.4:
var question = confirm("Do you want to continue
this download?”);
• After the user presses one of the buttons in the
confirm dialog window, the script can test the
variable, question, and react accordingly.

 

©

6.5 Screen Output
• The prompt
method creates a dialog window
that contains a text box. The text box is used to
collect a string of input from the user, which
prompt returns as its value. The window also
includes two buttons, OK and Cancel, prompt
takes two parameters, the string that prompts
the user for input and a default string in case the
user does not type a string before pressing one
of the two but-tons. In many cases, an empty
string is used for the default input. Consider this
example:
name = prompt("What is your name?, "");

 

©

6.5 Screen Output
• Figure 6.5 shows the screen created by
this call to prompt.
• alert, prompt, and confirm cause the
browser to wait for a user response. In the
cases of alert and prompt, the OK button
must be pressed for the JavaScript script
to continue. The confirm method waits for
either OK or Cancel to be pressed.

 

©

6.6 Control Statements
• This section introduces the statement
control flow statements of JavaScript.
• Control statements often require some
syntactic container for sequences of
statements whose execution they are
meant to control. In JavaScript, that
container
is the compound statement.
• A compound statement
in JavaScript is a
sequence of statements demited by
braces
.

 

©

6.6 Control Statements
• A control construct
is a control statement and
the statement or compound statement whose
execution it controls.
• Unke several related languages, JavaScript
does not allow compound statements to create
local variables.
• If a variable is declared in a compound
statement, access to it is not confined to that
compound statement. Such a variable is visible
in the whole HTML document. Local variables
are discussed in Section 6.9.2, "Local
Variables."

 

©

6.6.1 CONTROL
EXPRESSIONS
• The expressions upon which statement control
flow can be based include primitive values,
relational expressions, or compound
expressions.
• The result of evaluating a control expression is
one of the Boolean values, true or false.
• If the value of a control expression is a string, it
is interpreted as true unless it is either the empty
string (" ") or a zero string (" 0 "). If the value is a
number, it is true unless it is zero (0).
• A relational expression has two operands and
one relational operator. The relational operators
are shown in Table 6.5.

 

©

6.6.1 CONTROL
EXPRESSIONS
• If the two operands are not of the same
type and the operator is neither ===
nor !==, JavaScript will attempt to convert
the operands to a type that can be
compared. In the case in which one
operand is a string and the other is a
number, JavaScript attempts to convert
the string to a number. If one operand is
Boolean and the other is not, the Boolean
value is converted to a number (1 for true,
0 for false).

 

©

6.6.1 CONTROL
EXPRESSIONS
• The last two operators in Table 6.5 disallow type
conversion of either operand. So, the expression
"3" === 3 evaluates to false, while "3" == 3
evaluates to true.
• Comparisons of variables that reference
objects are rarely useful. If a and b
reference different objects, a == b is never
true, even if the objects have iden-tical
properties, a == b is true only if they
reference the same object.

 

©

6.6.1 CONTROL
EXPRESSIONS
• Comparisons of variables that reference
objects are rarely useful. If a and b
reference different objects, a == b is never
true, even if the objects have identical
properties, a == b is true only if they
reference the same object.

 

©

6.6.1 CONTROL
EXPRESSIONS
• JavaScript has operators for the AND, OR, and NOT
Boolean operations. These are && (AND), | | (OR),
and !(NOT). Both && and | | are short-circuit operators,
as they are in Perl, Java, and C++. This means that if the
value of the first operand of either | | or && determines
the value of the expression, the second operand is not
evaluated and the Boolean operator does nothing.
JavaScript also has bitwise operators, but they are not
discussed in this book.
• The properties of the object Boolean must not be
confused with the primitive values true and false. If a
Boolean object is used as a conditional expression, it
evaluates to true if it has any value other than null or
undefined. The Boolean object has a method, toString,
that converts the value of the object through which it is
called to one of the strings " true" or "false".

 

©

6.6.2 SELECTION
STATEMENTS
• The selection statements (if-then and ifthen-
else) of JavaScript z identical to
those of Perl, except that either single
statements or compound statements can
be selected rather than only compound
statements. For example although this
statement is syntactically illegal in Perl, it
is acceptable JavaScript:
• if (a > b) a = b;

 

©

6.6.3 THE switch
STATEMENT
• JavaScript has a switch statement that is exactly ke that
of C. The form this construct is shown here:
switch (expression) {
case value_1:
IIvalue_1 statements
case value_2:
// value_2 statements
• • •
[default:
// default statements]
}
Example in Page 207 ch6_1.htm

 

©

6.6.4 LOOP STATEMENTS
• The JavaScript while and for statements are
similar to those of Perl, Java, and C++. The
general form of the while statement is shown
here:
while (control expression)
statement or compound statement
• The general form of the for statement is this:
for (initial expression; control expression; increment expression)
statement or compound statement

 

©

6.6.4 LOOP STATEMENTS
• The following illustrates a simple for
construct:
var sum = 0,count;
for (count = 0; count <= 10; count++)
sum += count;

 

©

6.6.4 LOOP STATEMENTS
• In addition to the while and for loop
statements, JavaScript also has a do-while
statement, whose form is this:
do
statement or compound statement
while (control expression)

 

©

6.6.4 LOOP STATEMENTS
• The following is an example of a do-while
construct:
do {
count++;
sum = sum + (sum * count);
} while (count <= 50);
• JavaScript includes one more loop statement,
the for-in statement, which is most often used
with objects. The for-in statement is discussed in
Section 6.9, "Functions."

 

©

6.7 Object Creation and
Modification
• Objects are often created with a new expression, which
must include a call to a constructor method. The
constructor that is called in the new expression creates
the properties that characterize the new object.
• In an object-oriented language such as Java, the new
operator creates a particular object, meaning an object
with a type and a specific collection of members. So, in
Java the constructor initiazes members but does not
create them.
• In JavaScript, however, the new operator creates a blank
object, or one with no properties. JavaScript objects do
not have types. The constructor both creates and
initiazes the properties.

 

©

6.7 Object Creation and
Modification
• The following statement creates an object
that initially has no properties:
var my_object = new Object();
• The variable my_object now references
the new object. Calls to constructors must
include parentheses, even if there are no
parameters. Constructors are discussed in
detail in Section 6.11, "Constructors."

 

©

6.7 Object Creation and
Modification
• The properties of an object are accessed
using dot notation, in which the first word
is the object name and the second is the
property name. Properties are not actually
variables—they are keys into a hash, so
as with Perl hash keys, they have no
values of their own. They are used with
object variables to access property values.
Because properties are not variables, they
are never declared.

 

©

6.7 Object Creation and
Modification
• The number of members of a class in a
typical object-oriented language is fixed at
compile time. The number of properties in
a JavaScript object is dynamic. At any
time during interpretation, properties can
be added to or deleted from an object. A
property for an object is created by
assigning a value to that property.
Consider the following example:

 

©

6.7 Object Creation and
Modification
var my_car = new Object();
// Create a blank object
my_car.make = "Ford";
// Create and initiaze the make property
my_car.model = "Contour SVT";
// Create and initiaze model

 

©

6.7 Object Creation and
Modification
• Because objects can be nested, you can
create a new object that is a property of
my_car with properties of its own:
my_car.engine = new Object();
my_car.engine.config = "V6";
my__car.engine.hp = 200;

 

©

6.7 Object Creation and
Modification
• Properties can be accessed in two ways:
• First, any property can be accessed in the same way it is
assigned a value, using the object-dot-property notation.
var prop1 = my_car.make;
• Second, the property names of an object can be
accessed as if they were elements of an array, using the
property name as if it were a string teral. This is similar
to the way values in a Perl hash are accessed. For
example, consider the following statements:
var prop2 = my_car["make"];
• After executing these two statements, the variables
prop1 and prop2 both have the value "Ford".

 

©

6.7 Object Creation and
Modification
• If an attempt is made to access a property
of an object that does not exist, the value
undefined is used. A property can be
deleted with delete, as in this example:
delete my__car. model;

 

©

6.7 Object Creation and
Modification
• JavaScript has a loop statement, for-in,
that is perfect for sting the properties of
an object. This statement is related to the
Perl foreach statement. The form of for-in
is as follows:
for (identifier in object)
statement or compound statement

 

©

6.7 Object Creation and
Modification
• Take a look at this example:
for (var prop in my_car)
document.write("Name: " + prop + "? Value:
" + my_car[prop] + "<br/>");

 

©

6.8 Arrays
• Arrays in JavaScript are objects that have
some special functionaty. Array elements
can be primitive values or references to
other objects, including other arrays.
JavaScript arrays have dynamic length.

 

©

6.8.1 Array OBJECT
CREATION
• Array objects, unke most other JavaScript
objects, can be created in two distinct
ways.
• The usual way to create any object is with
the new operator and a call to a
constructor. In the case of arrays, the
constructor is named Array:
var my_st = new Array(1,2, "three", "four");
var your_st = new Array(100);

 

©

6.8.1 Array OBJECT
CREATION
• In the first declaration, a new Array object of
length 4 is created and initiazed. In the second,
a new Array object of length 100 is created,
without actually creating any elements .
• Whenever a call to the Array constructor has a
single parameter, that parameter is taken to be
the number of elements, not the initial value of a
one-element array.
• A program can always determine the length of
an array with the length property of the array's
object. Every Array object is given the length
property by the Array constructor.

 

©

6.8.1 Array OBJECT
CREATION
• The second way to create an Array object
is with a teral array value, which is a st
of values enclosed in brackets:
var my_st_2 = [1, 2,
"three", "four"];

 

©

6.8.2 CHARACTERISTICS
OF Array OBJECTS
• The lowest index of every JavaScript array
is zero. Array element access is specified
with numeric subscripts placed in brackets.
The length of an array is the highest
subscript to which a value has been
assigned, plus 1. So, if the assignment to
my_st that has the highest subscript is
the following, then the length of my_st is
48:
my_st[47] = 2222;

 

©

6.8.2 CHARACTERISTICS
OF Array OBJECTS
• The length of an array is both read- and writeaccessible
through the / length property.
Consequently, the length of an array can be set
to whatever you ke by assigning the length
property:
my_st.length = 1002;
• Now, the length of my_st is 1002, regardless of
what it was previously. Assigning a value to the
length property can lengthen, shorten, or not
affect the array's length (if the value assigned
happens to be the same as the previous length
of the array).

 

©

6.8.2 CHARACTERISTICS
OF Array OBJECTS
• Only the assigned elements of an array
actually occupy space.
• For example, if it is convenient to use the
subscript range of 100-150 but not 0-99,
an array of length 151 can be created. But
if only the elements indexed 100-150 are
assigned values, the array will require the
space of 51 elements, not 151.

 

©

6.8.2 CHARACTERISTICS
OF Array OBJECTS
• Remember that the length property of an
array is not necessarily the number of
defined or even allocated elements.
• All array elements are allocated
dynamically from the heap.

 

©

6.8.3 Array METHODS
• Array objects have a collection of useful
methods, which are described here.
• The join method, which is similar to the
join operator of Perl, converts all of the
elements of an array to strings and
catenates them together into a single
string. If no parameter is provided, the
element values in the new string are
separated by commas.

 

©

6.8.3 Array METHODS
• If a string parameter is provided, it is used
as the element separator:
var names = new Array["Mary", "Murray",
"Murphy", "Max"];

var name_string = names.join(" : ");
• The value of name_string is now "Mary :
Murray : Murphy :Max".

 

©

6.8.3 Array METHODS
• The reverse method does what you would
expect: It reverses the order of the elements of
the Array object through which it is called.
• The sort method coerces the elements of the
array to strings, if they are not already strings,
and sorts them into alphabetical order:
names.sort();
• The value of names is now [ “Mary", "Max",
"Murphy", "Murray" ].
• In Section 6.9, "Functions," we discuss the use
of sort for different orders and for different types
of elements.

 

©

6.8.3 Array METHODS
• The concat method catenates its actual
parameters to the end of the Array object on
which it is called. For example, consider this
code:
var names = ["Mary", "Murray", "Murphy", "Max"];
• • •
var new_names = names.concat("Moo", "Meow");
• The value of new_names variable has length 6,
with "Moo" and "Meow" as its fifth and sixth
elements.

 

©

6.8.3 Array METHODS
• The sce method does for arrays what the
substring method does for strings. It returns the
part of the Array object specified by its
parameters, which are used as subscripts. The
returned array has the elements of the array
object through which it is called from the first
parameter up to but not including the second
parameter—for example:
var st = [2, 4, 6, 8, 10];
• • •
var st2 = st.sce(1, 3);
• The value of st2 is now [ 4, 6 ].

 

©

6.8.3 Array METHODS
• If sce is given just one parameter, the
returned array has all of the elements of
the object, starting with the specified index:
var st = ["Bill", "Will", "Jill", "dill"];
• • •
var stette = st.sce(2);
• The value of stette is now [ "Jill", "dill" ].

 

©

6.8.3 Array METHODS
• When the toString method is called
through an Array object, each of the
elements of the object is converted (if
necessary) to a string. These strings are
catenated together, separated by commas.
So, in this case the toString method
behaves much ke join.
• The push, pop, unshift, and shift methods
of Array are closely related to their
corresponding operators in Perl.

 

©

6.8.3 Array METHODS
• The pop and push methods remove and
add an element to the end of an array,
respectively. For example, consider the
following code:
var st = ["Dasher", "Dancer", " Donner", "Btzen"];
var deer = st.pop(); // deer is "Btzen"
st.push("Btzen"); // puts "Btzen" back on st

 

©

6.8.3 Array METHODS
• The shift and unshift methods remove and
add an element to the beginning of an
array, respectively. For example, assume
that st is created as previously and
consider the following code:
var deer = st.shift() // deer is now "Dasher"
st.unshift("Dasher ") // puts "Dasher" back on st

 

©

6.8.3 Array METHODS
• A two-dimensional array is implemented in
JavaScript as an array of arrays. This can
be done with the new operator or with
nested array terals, as illustrated in the
following example:
• Page 215-216
Ch6_2.html

 

©

6.9 Functions
• Subprograms are central to the usefulness
of any programming language.
JavaScript's subprograms are all functions.
Although JavaScript functions are
modeled on the functions in C, there are
some important differences between the
two.

 

©

6.9.1 FUNDAMENTALS
• A function definition consists of the
function's header and a compound
statement that describes its actions.
– This compound statement is often called the
body of the function.
– A function header consists of the reserved
word function, the function's name, and a
parenthesized st of parameters, if there are
any.

 

©

6.9.1 FUNDAMENTALS
• A return statement returns control to the
function's caller.
– It optionally includes an expression, whose value is
returned by the function.
– A function body may include one or more return
statements.
– If there are no return statements in a function, or if the
specific return that is executed does not include an
expression, the returned value is undefined.
– This is also the case if execution reaches the end of
the function body without executing a return
statement.

 

©

6.9.1 FUNDAMENTALS
• A call to a function with no parameters is the function's
name followed by an empty pair of parentheses.
• A call to a function that returns undefined is a
stand-alone statement.
• A call to a function that returns a useful value appears as
the operand in an expression (often the whole right side
of an assignment statement).
• For example, if fun1 is a parameterless function that
returns undefined, and if fun2, which also has no
parameter, returns a useful value, they can be called
with this code:
fun1();
result = fun2();

 

©

6.9.1 FUNDAMENTALS
• JavaScript functions are objects.
– so variables that reference them can be treated as
other object references.
– They can be passed as parameters, assigned to other
variables, and can be the elements of an array.
• Take a look at this example:
function fun() { document.write("This surely is funi
<br/>");}
ref_fun = fun; // Now, ref_fun refers to the fun
object
fun(); // a call to fun
ref_fun(); // Also a call to fun function.htm

 

©

6.9.1 FUNDAMENTALS
• To ensure that the interpreter sees the
definition of a function before it sees a call
to the function, function definitions are
placed in the head of an HTML document.
Calls to functions appear only in the
document body.

 

©

6.9.2 LOCAL VARIABLES
• The scope of a variable is the range of
statements over which it is visible. When
JavaScript is embedded in an HTML
document, the scope of a variable is the
range of nes of the document over which
the variable is visible.

 

©

6.9.2 LOCAL VARIABLES
• A variable that is not declared with a var
statement is impcitly declared by the JavaScript
system at the time it is first encountered in the
script.
• Variables that are impcitly declared, even if the
impcit declaration occurs within a function
definition, have global scope —that is, they are
visible in the entire HTML document.
• Variables that are expcitly declared outside a
function definition also have global scope. As
stated earer, we recommend that all variables
be expcitly declared.

 

©

6.9.2 LOCAL VARIABLES
• It is usually best for variables that are used
only within a function to have local scope,
meaning that they are visible and can be
used only within the body of the function.
• Any variable expcitly declared with var in
the body of a function has local scope.

 

©

6.9.2 LOCAL VARIABLES
• Although JavaScript function definitions
can be nested, the need for nested
functions in cent-side JavaScript is mited.
Furthermore, they can greatly compcate
scripts. Therefore, we do not recommend
the use of nested functions and do not
discuss them here.

 

©

6.9.2 LOCAL VARIABLES
• If a variable appears in a script that is defined
both as a local variable and as a global variable,
the local variable has precedence, effectively
hiding the global variable with the same name.
• This is the advantage of local variables: When
you make up their names, you need not be
concerned that a global variable with the same
name may exist somewhere in the collection of
scripts in the HTML document.

 

©

6.9.3 PARAMETERS

 

©

6.9.3 PARAMETERS
• The parameter values that appear in a call to a function
are called actual parameters. The parameter names that
appear in the header of a function definition which
correspond to the actual parameters in the function calls,
are called for mal parameters.
• JavaScript uses the pass-by-value parameter-passing
method When a function is called, the values of the
actual parameters specified in the call are, in effect,
copied into their corresponding formal parameters, which
behave exactly as local variables. Because references
are passed as the actual parameters for objects, the
function has access to the objects and can change them,
thereby providing the semantics of pass-by-reference
parameters.

 

©

6.9.3 PARAMETERS
• Because of JavaScript's dynamic typing, there is
no type checking of parameters. The called
function can itself check the types of parameters
with the typeof operator. However, recall that
typeof cannot distinguish between different
objects. The number of parameters in a function
call is not check against the number of formal
parameters in the called function. In the function,
excess actual parameters that are passed are
ignored; excess formal parameters are set to
undefined.

 

©

6.9.3 PARAMETERS
• All parameters are communicated through a
property array, arguments, which, ke other
array objects, has a property named length. By
accessing arguments.length, a function can
determine the number of actual parameters that
were passed. Because the arguments array is
accessible directly, all actual parameters
specified in the call are available, including
actual parameters that do not correspond to any
formal parameters (because there were more
actual parameters than formal parameters).
Consider the following example: Page 219.
Ch6_3.html

 

©

6.9.4 THE sort OPERATOR,
REVISITED
• Recall that the sort method for array objects converts the
array’s elements to strings, if necessary, and then sorts
them into alphabetical order. If you need to sort
something other than strings, or if you want some order
other than alphabetic for strings, the comparison
operation must be supped to the sort method by the
user.
• Such a comparison operation is passed as a parameter
to sort. The comparison function must return a negative
number if the two elements being compared are in the
desired order, zero if they are equal, and a number
greater than zero if they must be interchanged. For
example, if you want to sort the array of numbers
num_st into ascending order using the sort method.
• Example page 222
order_num.htm

 

©

6.10 An Example
• The flowing is an example of an HTML
document containing a JavaScript function to
compute the median of an array of numbers.
The function first sorts the array using the sort
method. If the given array has an odd length, the
median is computed as the middle element. The
middle element is determined by dividing the
length by 2 and truncating the result using floor.
If the length is even, the median is the average
of the two middle elements. The result of the
average computation is rounded to an integer
using round.
• Example Page 222-224 Ch6_4.html

 

©

6.11 Constructors
• JavaScript constructors are special methods that
create and initiaze the properties for newly
created objects. Every new expression must
include a call to a constructor, whose name is
the same as the object being created. As you
saw in Section 6.8, "Arrays," for example, the
constructor for arrays is named Array.
• Constructors are actually called by the new
operator, which immediately precedes them in
the new expression.

 

©

6.11 Constructors
• A constructor obviously must be able to
reference the object on which it is to
operate. JavaScript has a predefined
reference variable for this purpose, named
this. When the constructor is called, this is
a reference to the newly created object.
The this variable is used to construct and
initiaze the properties of the object. For
example, consider the following
constructor:

 

©

6.11 Constructors
function car(new_make, new_model,
new_year) {
this. make = new_make;
this.model == new_model;
this.year = new_year; }
• This constructor could be used as in the
following:
my_car = new car("Ford", "Contour SVT",
"2000 ");

 

©

6.11 Constructors
• So far we have considered only data
properties. If a method is to be included in
the object, it is initiazed the same way as
if it were a data property.
• For example, suppose that you wanted a
method for car objects that sted the
property values. Such a function could be
written as follows:

 

©

6.11 Constructors
function display_car() {
document.write("Car make: ", this.make, "<br/>");
document.write("Car model: ", this.model, "<br/>");
document.write("Car year: ", this.year, "<br/>"); }
• The following ne must be added to the
constructor:
this.display = display_car;

 

©

6.11 Constructors
• The only concept of categories of objects
in JavaScript that is related to the concept
of class in an object-oriented programming
language is the collection of objects
created using the same constructor. All
such objects would have the same set of
properties and methods, at least initially.
However, there is no convenient way to
determine in the script whether two objects
have the same set of properties and
methods.

 

©

6.12 Pattern Matching
• Chapter 4 briefly described the patternmatching
facities of Perl (see Section
4.10, "Pattern Matching Using Regular
Expressions"). The designers of
JavaScript copied the syntax and
semantics of patterns from Perl. However,
the way patterns are used is different in
JavaScript.

 

©

6.12 Pattern Matching
• A pattern-matching operation can be
specified with one of the pattern-matching
methods of a String object, using the
pattern as the parameter to the method.
• The search method of String corresponds
to the m operator in Perl.
• The String object through which search is
called is searched using the pattern given
in the parameter.

 

©

6.12 Pattern Matching
• The search method returns the position of
the first character of the match in the string,
where the position of the first character in
the string is 0.
• The value -1 is returned if there is no
match. For example, consider this code:
var str = "Abernathy";
var position = str.search(/er/); Matching.htm

 

©

6.12 Pattern Matching
• The replace method corresponds to the substitute
operator in Perl. The replace method takes two
parameters, the pattern and the replacement string.
• The g modifier can be attached to the pattern if the
replacement is to be global in the string, in which case
the replacement is done for every match in the string.
• The matched substrings of the string are made available
through the variables $1, $2, ...Just as in Perl. For
example, consider these statements:
var str = "Fred, Freddie, and Frederica were sibngs";
str.replace(/Fre/g, "Boy");
• In this example, str is set to "Boyd, Boyddie, and
Boyderica were sibngs", and $1, $2, and $3 are all set
to "Fre".

 

©

6.12 Pattern Matching
• The match method is the most general of the String
pattern-matching methods. The match method takes a
single parameter, the pattern. It returns an array of the
results of the pattern-matching operation.
• If the pattern has the g modifier, the returned array has
all of the substrings of the string that matched.
• If the pattern does not include g, the returned array has
the match as its first element, and the remainder of the
array has the matches of parenthesized parts of the
pattern, if there are any (in other words, the values of $1,
$2,...):
var str = "Having 4 apples is better than having 3 oranges";
var matches = str.match(//d/g);
• In this example, matches is set to [ 4, 3 ].

 

©

6.12 Pattern Matching
• The spt method of String corresponds to the spt
operator in Perl. It is given the pattern on which the spt
is to be done, and it returns an array of the substrings
into which the string was spt:
var str = "grapes : apples : oranges";
var fruit = str.spt(":");
• In this example, fruit is set to [ grapes, apples, oranges ].
The parameter to spt can be either a string or a regular
expression.
• There is a second way to do pattern matching in
JavaScript. A pattern can be a RegExp object, in which
case the methods of that object are used and the string
on which the pattern is to be matched is sent as the
parameter to the method. We do not discuss the use of
RegExp objects for pattern matching.

 

©

6.13 Another Example
• One of the common uses for JavaScript is to check the
correctness of input from HTML forms, which is
discussed in detail in Chapter 7, "JavaScript and HTML
Documents." The example in this section illustrates the
use of a simple function to check a given string that is
supposed to contain a phone number to determine
whether its form is correct. The function uses a simple
pattern match to check the phone number. Once again,
we include the complete HTML document with the
embedded JavaScript.
• The display generated by Ch6_5. html is shown in Figure
6.9. in page 230
• Page 228-229

 

©

6.14 Summary
• Cent-side JavaScript scripts are
embedded in HTML files as the content of
<script> tags. A file containing a script can
be included by specifying its name as the
value of the <script> tag attribute src.
• Values in JavaScript are either primitives
or objects.
• JavaScript is dynamically typed, which is
not the same as being a typeless
language.

 

©

6.14 Summary
• A variable has a type, but that type can change
every time a new value is
assigned to the
variable. It is best to expcitly declare all
variables.
• The Number object includes a collection of
useful properties, such as MIN_VALUE and PI.
• The alert method of Window produces output in
a dialog box.
• The confirm method of Window asks the user for
input through OK and Cancel buttons.
• The prompt method of Window asks the user for
textual input.

 

©

6.14 Summary
• The docu-ment, write method dynamically
produces HTML content. The control statements
of JavaScript are closely related to those of Perl,
except that JavaScript includes a switch
statement. Also, JavaScript uses a sghtly
differ-ent collection of relational operators.
• Function definitions name their formal
parameters but do not include type names.
• The primary difference is how the patterns are
used. In JavaScript, pattern matches are
specified by one of the methods of the String
object.

 

©

6.16 Exercises
• Page 233-246
– 2
– 5
– 10
– 14