0% found this document useful (0 votes)
5K views16 pages

Javascript Notes

The document provides an overview of JavaScript, including its primitive data types, operators, expressions, screen output and keyboard input, control statements, objects and constructors, arrays, functions, and pattern matching. It discusses the differences between JavaScript and Java, including that JavaScript is dynamically typed while Java is statically typed. The original goal of JavaScript was to provide programming capabilities on both the client and server sides of a web connection. Client-side JavaScript can offload some server-side processing to the client but cannot replace all server-side computing like file operations and database access. JavaScript uses prototype-based inheritance rather than class-based inheritance.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
5K views16 pages

Javascript Notes

The document provides an overview of JavaScript, including its primitive data types, operators, expressions, screen output and keyboard input, control statements, objects and constructors, arrays, functions, and pattern matching. It discusses the differences between JavaScript and Java, including that JavaScript is dynamically typed while Java is statically typed. The original goal of JavaScript was to provide programming capabilities on both the client and server sides of a web connection. Client-side JavaScript can offload some server-side processing to the client but cannot replace all server-side computing like file operations and database access. JavaScript uses prototype-based inheritance rather than class-based inheritance.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 16

1 OVERVIEW OF JAVASCRIPT

2 OBJECT ORIENTATION AND JAVASCRIPT


3 GENERAL SYNTACTIC CHARACTERISTICS
4 PRIMITIVES, OPERATIONS, AND EXPRESSIONS
5 SCREEN OUTPUT AND KEYBOARD INPUT
6 CONTROL STATEMENTS
7 OBJECT CREATION AND MODIFICATION
8 ARRAYS
9 FUNCTIONS
10 AN EXAMPLE
11 CONSTRUCTORS
12 PATTERN MATCHING US
13 ANOTHER EXAMPLE
14 ERRORS IN SCRIPTS

primitive data types and their operators and expressions, screen output and keyboard input, controlstatements,
objects and constructors, arrays, functions, and pattern matching. The core is the heart of the language, including its
operators, expressions,statements, and subprograms. Client-side JavaScript is a collection of objects that support the control
of a browser and interactions with users. JavaScript, an XHTML document can be made to be responsive to user inputs such
as mouse clicks and keyboard use. Server-side JavaScript is a collection of objectsthat make the language useful on a Web
server—for example, to support communication with a database management system. Server-side JavaScript is used far
lessfrequently than client-side JavaScript

JavaScript and Java


Java is a strongly typed language. Types are all known at compile time, and operand types are checked for compatibility.
Variables in JavaScript need not be declared and are dynamically typed, making compile-time type checking impossible. One
more important difference between Java and JavaScript is that objects in Java are static in the sense that their collection of
data members and methods is fixed at compile time. JavaScript objects are dynamic: The number of data members and
methods of an object can change during execution.

The original goal of JavaScript was to provide programming capability at both the server and the client ends of a Web
connection.
Client-side JavaScript can serve as an alternative for some of what is done with server-side programming, in which
computational capability resides on the server and is requested by the client. Because client-side JavaScript is embedded in
XHTML documents (either physically or logically) and is interpreted by the browser, thistransfer of load from the often
overloaded server to the often underloaded client can obviously benefit other clients. Client-side JavaScript cannot replace all
server-sidecomputing, however. In particular, although server-side software supports file operations, database access, and
networking, client-side JavaScript supports none ofthese. Interactions with users through form elements, such as buttons and
menus, can be conveniently described in JavaScript. Because button clicks and mouse movements are easily detected with
JavaScript, they can be used to trigger computations and provide feedback to the user

Object Orientation and JavaScript


As stated previously, JavaScript is not an object-oriented programming language. Rather, it is an object-based language.
JavaScript does not have classes. Its objects serve both as objects and as models of objects. Without classes, JavaScript
cannot have class-based inheritance, which is supported in object-oriented languages suchas C++ and Java. It does, however,
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

JavaScript Objects

In JavaScript, objects are collections of properties, which correspond to the members of classes in Java and C++. Each
property is either a data property or a function or method property. Data properties appear in two categories: primitive values
and references to other objects. (In JavaScript, variables that refer to objects are oftencalled objects rather than references.)
Sometimes we will refer to the data properties simply as properties; we often refer to the method properties simply as methods
orfunctions. We prefer to call subprograms that are called through objects methods and subprograms that are not called
through objects functions.

General Syntactic Characteristics

Scripts can appear directly as the content of a <script> tag

The type attribute of <script> must be set to “text/javascript”. The JavaScript script can be indirectly embedded in an
XHTML document with the src attribute of a <script> tag, whose value is the name of a file that contains the script—for
example,

<script type = “text/javascript” src = “tst_number.js” >


</script>
The XHTML comment used to hide JavaScript uses the normal beginning syntax, <!--. However, the syntax for closing such
a comment is special. It is the usual XHTML comment closer, but it must be on its own line and must be preceded by two
slashes (which makes it a JavaScript comment). The following XHTML comment form hides the enclosed script from browsers
that do not have JavaScript interpreters, but makes it visible to browsers that do support JavaScript:

4.4 Primitives, Operations, and Expressions

The primitive data types, operations, and expressions of JavaScript are similar to those of other common programming
languages. Therefore, our discussion of them isbrief.

4.4.1 Primitive Types


JavaScript has five primitive types: Number, String, Boolean, Undefined, and Null. Each primitive value has one of these types.
JavaScript includes predefinedobjects that are closely related to the Number, String, and Boolean types, named Number,
String, and Boolean, respectively. (Is this confusing yet?) Theseobjects are called wrapper objects. Each contains a property
that stores a value of the corresponding primitive type. The purpose of the wrapper objects is to provideproperties and
methods that are convenient for use with values 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 type primitive values and Number
objects and between the String typeprimitive values and String objects, the methods of Number and String can be used on
variables of the corresponding primitive types.
In fact, in most casesyou can simply treat Number and String type values as if they were objects.The difference between
primitives and objects is shown in the following example. Suppose that prim is a primitive variable with the value 17 and obj
is aNumber object whose property value is 17.
4.4.2 Numeric and String Literals
All numeric literals are values of type Number. The Number type values are represented internally in double-precision floating-
point form. Because of this singlenumeric data type, numeric values in JavaScript are often called numbers. Literal numbers in
a script can have the forms of either integer or floating-point values.Integer literals are strings of digits. Floating-point literals
can have decimal points, exponents, or both. Exponents are specified with an uppercase or lowercase e and apossibly signed
integer literal. The following are valid numeric literals:

72 7.2 .72 72. 7E2 7e2 .7e2 7.e2 7.2E-2

4.4.3 Other Primitive Types


The only value of type Null is the reserved word null, which indicates no value. A variable is null if it has not been explicitly
declared or assigned a value.If an attempt is made to use the value of a variable whose value is null, it will cause a runtime
error.The only value of type Undefined is undefined. Unlike null, there is no reserved word undefined. If a variable has been
explicitly declared, but notassigned a value, it has the value undefined. If the value of an undefined variable is displayed, the
word “undefined” is displayed.

4.4.4 Declaring Variables


One of the characteristics of JavaScript that sets it apart from most common non-scripting programming languages is that it is
dynamically typed. This means that avariable can be used for anything. Variables are not typed; values are. A variable can
have the value of any primitive type, or it can be a reference to any object. Thetype of the value of a particular appearance of a
variable in a program can be determined by the interpreter. In many cases, the interpreter converts the type of a valueto
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 implicitly declares it to be a variable, or
by listing it in a declarationstatement that begins with the reserved word var. Initial values can be included in a var
declaration, as with some of the variables in the following declaration:
4.4.5 Numeric Operators
JavaScript has the typical collection of numeric operators: the binary operators + for addition, - for subtraction, * for
multiplication, / for division, and % for modulus.
The unary operators are plus (+), negate (-), decrement (--), and increment (++). The increment and decrement operators can
be either prefix or postfix.
As withother languages that have the increment and decrement unary operators, the prefix and postfix uses are not always
equivalent. Consider an expression consisting of asingle variable and one of these operators. If the operator precedes the
variable, the value of the variable is changed and the expression evaluates to the new value. Ifthe operator follows the variable,
the expression evaluates to the current value of the variable and then the value of the variable is changed. For example, if the
variable

4.4.7 The Number Object


The Number object includes a collection of useful properties that have constant values. Table 4.3 lists the properties of
Number. These properties are referencedthrough Number. For example,
Number.MIN_VALUE

references the smallest representable number on the computer being used.Any arithmetic operation that results in an
error (e.g., division by zero) or that produces a value that cannot be represented as a double-precision floating-pointnumber,
such as a number that is too large (an overflow), returns the value “not a number,” which is displayed as NaN. If NaN is
compared for equality against anynumber, the comparison fails. Surprisingly, in a comparison, NaN is not equal to itself. To
determine whether a variable has the NaN value, the predefined predicatefunction isNaN() must be used. For example, if the
variable a has the NaN value, isNaN(a) returns true.The Number object has a method, toString, which it inherits from
Object but overrides. The toString method converts the number through which itis called to a string. Because numeric
primitives and Number objects are always coerced to the other when necessary, toString can be called through a
numericprimitive, as in the following code:

4.4.11 String Properties and Methods


Because JavaScript coerces primitive string values to and from String objects when necessary, the differences between the
String object and the String typehave little effect on scripts. String methods can always be used through String primitive
values, as if the values were objects. The String object includes oneproperty, length, and a large collection of methods.The
number of characters in a string is stored in the length property as follows:

varstr = “George”;
varlen = str.length;

T h e typeof operator returns the type of its single operand. This operation is quite useful in some circumstances in a script.
typeof produces “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 produces“object”. This example illustrates a fundamental
characteristic of JavaScript: Objects do not have types. If the operand is a variable that has not been assigned avalue, typeof
produces “undefined”, reflecting the fact that variables themselves are not typed. Notice that the typeof operator always
returns a string. Theoperand for typeof can be placed in parentheses, making it appear to be a function. Therefore, typeof x
and typeof(x) are equivalent.
4.4.13 Assignment Statements
The assignment statement in JavaScript is exactly like the assignment statement in other common C-based programming
languages. There is a simple assignmentoperator, denoted by =, and a host of compound assignment operators, such as +=
and /=. For example, the statement

a += 7;
means the same as

a = a + 7;

In considering assignment statements, it is important to remember that JavaScript has two kinds of values: primitives and
objects. A variable can refer to aprimitive value, such as the number 17, or an object, as shown in Figure 4.1. Objects are
allocated on the heap, and variables that refer to them are essentiallyreference variables. When used to refer to an object, a
variable stores an address only. Therefore, assigning the address of an object to a variable is fundamentallydifferent from
assigning a primitive value to a variable.

4.4.14 TheDate Object


There are occasions when information about the current date and time is useful in a program. Likewise, sometimes it is
convenient to be able to create objects thatrepresent a specific date and time and then manipulate them. These capabilities are
available in JavaScript through the Date object and its rich collection of methods.In what follows, we describe this object and
some of its methods.

A Date object is created with the new operator and the Date constructor, which has several forms. Because we focus on uses
of the current date and time, weuse only the simplest Date constructor, which takes no parameters and builds an object with
the current date and time for its properties. For example, we might have

var today = new Date();

The date and time properties of a Date object are in two forms: local and Coordinated Universal Time (UTC, which was
formerly named Greenwich MeanTime). We deal only with local time in this section.

4.6 Control Statements


This section introduces the flow-control statements of JavaScript. Before discussing the control statements, we must describe
control expressions, which provide thebasis for controlling the order of execution of statements. Once again, the similarity of
these JavaScript constructs to their counterparts in Java and C++ makes themeasy to learn for those who are familiar with one
of those languages.
Control statements often require some syntactic container for sequences of statements whose execution they are meant to
control. In JavaScript, that container isthe compound statement. A compound statement in JavaScript is a sequence of
statements delimited by braces. A control construct is a control statement together withthe statement or compound statement
whose execution it controls.
Unlike 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 XHTML document.
4.6.1 Control Expressions
The expressions upon which statement flow control can be based include primitive values, relational expressions, and
compound expressions. The result of evaluatinga control expression is one of the Boolean values true and false. If the value
of a control expression is a string, it is interpreted as true unless it is either theempty string (““) or a zero string (“0”). If the
value is a number, it is true unless it is zero (0). If the special value, NaN, is interpreted as a Boolean, it is false. Ifundefined is
used as a Boolean, it is false. When interpreted as a Boolean, null is false. When interpreted as a number, true has the value
1 and false hasthe value 0.
A relational expression has two operands and one relational operator. Table 4.6 lists the relational operators.
4.6.2 Selection Statements
The selection statements (if-then and if-then-else) of JavaScript are similar to those of the common programming
languages. Either single statements orcompound statements can be selected—for example,

4.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 theproperties 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 anda specific collection of members. Thus, in
Java, the constructor initializes members but does not create them. In JavaScript, however, the new operator creates a
blankobject—that is, one with no properties. Furthermore, JavaScript objects do not have types. The constructor both creates
and initializes the properties.
The following statement creates an object that has no properties:
varmy_object = new Object();

4.8 Arrays

In JavaScript, arrays are objects that have some special functionality. Array elements can be primitive values or references to
other objects, including other arrays.JavaScript arrays have dynamic lengths.

4.8.1 Array Object Creation


Array objects, unlike 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 aconstructor. In the case of arrays, the constructor is named Array:

4.8.3 Array Methods


Array objects have a collection of useful methods, most of which are described in this section. The join method converts all
of the elements of an array to stringsand catenates them into a single string. If no parameter is provided to join, the values in
the new string are separated by commas. If a string parameter is provided, it
is used as the element separator. Consider the following example:

4.9 Functions

JavaScript functions are similar to those of other C-based languages, such as C and C++.

4.9.1 Fundamentals

A function definition consists of the function’s header and a compound statement that describes the actions of the function.
This compound statement is called the bodyof the function. A function header consists of the reserved word function, the
function’s name, and a parenthesized list of parameters if there are any. Theparentheses are required even if there are no
parameters.
A return statement returns control from the function in which it appears to the function’s caller. Optionally, it includes an
expression, whose value is returnedto the caller. 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 isexecuted does not include an expression, the value returned is
undefined. This is also the case if execution reaches the end of the function body without executing

areturn statement (an action that is valid).


Syntactically, a call to a function with no parameters states the function’s name followed by an empty pair of parentheses. A
call to a function that returnsundefined is a standalone statement. A call to a function that returns a useful value appears as
an operand in an expression (often, the whole right side of anassignment statement). For example, if fun1 is a parameterless
function that returns undefined, and if fun2, which also has no parameters, returns a useful
value, they can be called with the following code:

fun1();
result = fun2();

JavaScript functions are objects, so variables that reference them can be treated as are other object references—they can be
passed as parameters, be assigned toother variables, and be the elements of an array. The following example is illustrative:

4.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 XHTML
document, the scope of a variable is the rangeof lines of the document over which the variable is visible.A variable that is not
declared with a var statement is implicitly declared by the JavaScript interpreter at the time it is first encountered in the script.
Variables thatare implicitly declared have global scope—that is, they are visible in the entire XHTML document (or entire file if
the script is in its own file)—even if the implicitdeclaration occurs within a function definition. Variables that are explicitly
declared outside function definitions also have global scope. As stated earlier, werecommend that all variables be explicitly
declared.
4.11 Constructors
JavaScript constructors are special methods that create and initialize the properties of newly created objects. Every new
expression must include a call to a constructorwhose name is the same as that of the object being created. As you saw in
Section 4.8, for example, the constructor for arrays is named Array. Constructors areactually called by the new operator,
which immediately precedes them in the new expression.Obviously, a constructor must be able to reference the object on
which it is to operate. JavaScript has a predefined reference variable for this purpose, namedthis. When the constructor is
called, this is a reference to the newly created object. The this variable is used to construct and initialize the properties of
theobject. For example, the constructor
CHAPTER 6
DYNAMIC DOCUMENTS WITH JAVASCRIPT

6.1 INTRODUCTION
6.2 POSITIONING ELEMENTS
6.3 MOVING ELEMENTS
6.4 ELEMENT VISIBILITY
6.5 CHANGING COLORS AND FONTS
6.6 DYNAMIC CONTENT
6.7 STACKING ELEMENTS
6.8 LOCATING THE MOUSE CURSOR
6.9 REACTING TO A MOUSE CLICK
6.10 SLOW MOVEMENT OF ELEMENTS
6.11 DRAGGING AND DROPPING ELEMENTS

Dynamic XHTML is not a new markup language. It is a collection of technologies that allows dynamic changes to documents
defined with XHTML. Specifically, a dynamic XHTML document is an XHTML document whose tag attributes, tag contents, or
element style properties can be changed by user interaction or the occurrence of a browser event after the document has
been, and is still being, displayed. Such changes can be made with an embedded script that accesses the elements of the
document as objects in the associated DOM structure.

Positioning Elements

It provides the means not only to position any element anywhere in the display of a document, but also to movean element to a
new position in the display dynamically, using JavaScript to change the positioning style properties of the elementThe
absolute value is specified for position when the element is to be placed at a specific place in the document display without
regard to the positions of
other elements. For example, if a paragraph of text is to appear 100 pixels from the left edge and 200 pixels from the top of the
display window, the following elementcould be used:
Relative Positioning

An element that has the position property set to relative, but does not specify top and left property values, is
placed in the document as if the position attribute were not set at all. However, such an element can be moved later. If the
top and left properties are given values, they displace the element by the specified amount from the position where it would
have been placed (if top and left had not been set). For example, suppose that two buttons are placed in a document and the
position attribute has its default value, which is static. Then the buttons would appear next to each other in a row,
assuming that the current row has sufficient horizontal space for them.it can be used to create superscripts and subscripts by
placing the values to be raised or lowered in <span> tags and displacing them from their regular positions.
6.2.3 Static Positioning
The default value for the position property is static. A statically positioned element is placed in the document as if it had
the position value of relative but no values for top or left were given. The difference is that a statically positioned
element cannot have its top or left properties initially set or changed later. Therefore, a statically placed element cannot be
displaced from its normal position and cannot be moved from that position later.
6.3 Moving Elements
As stated previously, an XHTML element whose position property is set to either absolute or relative can be moved.
Moving an element is simple: Changing the top or left property values causes the element to move on the display. If its
position is set to absolute, the element moves to the new values of top and left; if its position is set to relative, it
moves from its original position by distances given by the new values of top and left. In the next example, an image is
absolutely positioned in the display. The document includes two text boxes, labeled x coordinate and y coordinate,
respectively. The user can enter new values for the left and top properties of the image in these boxes. When the button
labeled Move It is pressed, the values ofthe left and top properties of the image are changed to the given values, and the
element is moved to its new position.A JavaScript function, stored in a separate file, is used to change the values of left and
top in this example. Although it is not necessary here, the id of the element to be moved is sent to the function that does the
moving, just to illustrate that the function could be used on any number of different elements. The values of the two text boxes
are also sent to the function as parameters. The actual parameter values are the DOM addresses of the text boxes, with the
valueattribute attached, which provides the complete DOM addresses of the text box values. Notice that style is attached to
the DOM address of the image to be moved becausetop and left are style properties. Because the input top and left values
from the text boxes are just string representations of numbers, but the top and left properties must end with some unit
abbreviation, the event handler catenates“px” to each value before assigning it to the top and left properties. This
document, called mover.html, and the associated JavaScript file, mover.js, are as follows:

6.4 Element Visibility


Document elements can be specified to be visible or hidden with the value of their visibility property. The two possible
values for visibility are, quite naturally, visible and hidden. The appearance or disappearance of an element can be
controlled by the user through a widget.

6.5 Changing Colors and Fonts


The background and foreground colors of the document display can be dynamically changed, as can the font properties of the
text.
6.5.1 Changing Colors

Dynamic changes to colors are relatively simple. In the next example, the user is presented with two text boxes into which
color specifications can be typed—one for the document background color and one for the foreground color. The colors can
be specified in any of the three ways that color properties can be given in CSS. A JavaScript function that is called whenever
one of the text boxes is changed makes the change in the document’s appropriate color property: back-groundColoro
rcolor. The first of the two parameters to the function specifies whether the new color is for the background or foreground;
the second specifies the new color.The new color is the value property of the text box that was changed by the user. In this
example, the calls to the handler functions are in the XHTML text box elements. This approach allows a simple way to
reference the element’s DOM address. The JavaScript this variable in this situation is a reference to the object that represents
the element in which it is referenced. A reference to such an object isits DOM address. Therefore, in a text element, the value of
this is the DOM address of the text element. So, in the example, this.value is used as an actual parameter to the handler
function. Because the call is in an input element, this.value is the DOM address of the value of the input element. This
document, called dynColors.html, and the associated JavaScript file are as follows:
6.5.2 Changing Fonts
Web users are accustomed to having links in documents change color when the cursor is placed over them. Use of the
mouseover event to trigger a JavaScript event handler allows us to change any property of any element in a document,
including text, when the mouse cursor is placed over it. Thus, the font style and font size, as well as the color and background
color of text, can be changed when the cursor is placed over the text. The text can be changed back to its original form when
an event handler is triggered with the mouseout event. For CSS attribute names that are single words without hyphens, the
associated JavaScript property names are the same as the attribute names. But when an attribute name includes a hyphen, as
in font-size, the associated property name must be different (because a property name cannot include a hyphen). The
convention is that when an attribute name has a hyphen, the hyphen is deleted and the letter that follows is capitalized in its
associated property name. So, the property name associated with the attribute font-size is fontSize.
6.7 Stacking Elements
The top and left properties allow the placement of an element anywhere in the two dimensions of the display of a document.
Although the display is restricted to two physical dimensions, the effect of a third dimension is possible through the simple
concept of stacked elements, such as that used to stack windows in graphical user interfaces. Although multiple elements can
occupy the same space in the document, one is considered to be on top and is displayed. The top element hides the parts of
the lower elements on which it is superimposed. The placement of elements in this third dimension is controlled by the z-
index attribute of the element. Anelement whose z-index is greater than that of an element in the same space will be
displayed over the other element, effectively hiding the element with the smaller z-index value. The JavaScript style property
associated with the z-index attribute is zIndex.In the next example, three images are placed on the display so that they
overlap. In the XHTML description of this situation, each image tag includes an onclick attribute, which is used to trigger the
execution of a JavaScript handler function. First the function defines DOM addresses for the last top element and the new top
element. Then the function sets the zIndex value of the two elements so that the old top element has a value of 0 and the new
top element has the value 10, effectively putting it at the top. The script keeps track of which image is currently on top with the
global variable top, which is changed every time a new element is moved to the top with the toTop function. Note that the
zIndex value, as is the case with other properties, is a string. This document, called stacking.html
6.11 Dragging and Dropping Elements
One of the more powerful efects of event handling is allowing the user to drag and drop elements around the display screen.
The mouseup, mousedown, and mousemove events can be used to implement this feature. Changing the top and left
properties of an element, as seen earlier in the chapter, causes the element to move. To illustrate drag and drop, an XHTML
document and a JavaScript file that creates a magnetic poetry system is developed, showing two static lines of a poem and
allowing the user to create the last two lines from a collection of movable words.

You might also like