0% found this document useful (0 votes)
34 views57 pages

Unit 3 Up

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
0% found this document useful (0 votes)
34 views57 pages

Unit 3 Up

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/ 57

JavaScript is one of the 3 languages all web developers must learn.

1. HTML to define the content of web pages


2. CSS to specify the layout of web pages
3. JavaScript to program the behavior of web pages

 JavaScript can change HTML content


 JavaScript can change CSS style properties
 JavaScript can validate input
 JavaScript can change HTML attributes
 JavaScript can make interactions with users through form elements, such as buttons and menus

Three parts of Javascript:


Core JavaScript
Includes operators, expressions, statements and subprograms (heart of language)
Client-side JavaScript
A collection of objects that support control of browser and interactions with user. Eg: with javascript, an
HTML document can be made to respond to user inputs such as mouse clicks and keyboard use.
Server-side JavaScript
A collection of objects that make the language useful on a web server. For eg: to support communication
with a DBMS, file operations and networking.

 Scripts can appear directly as the content of a <script> tag. The type attribute of <script>
must be set to "text/javascript".
<!DOCTYPE.html>
<!-- hello.html
A trivial hello world example of HTML/JavaScript
-->
<html lang = "en">
<head>
<title> Hello world </title>
<meta charset = "utf-8" />
</head>
<body>
<script type = "text/javascript">
<!--
document.write("Hello, fellow Web programmers!");
// -->
</script>
</body>
</html>

1
 The JavaScript script can be indirectly embedded in an HTML 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>
Example:
<!DOCTYPE html>
<!-- roots.html
A document for roots.js
-->
<html lang = "en">
<head>
<title> roots.html </title>
<meta charset = "utf-8" />
</head>
<body>
<script type = "text/javascript" src = "roots.js" >
</script>
</body>
</html>

// roots.js
// Compute the real roots of a given quadratic
// equation. If the roots are imaginary, this script
// displays NaN, because that is what results from
// taking the square root of a negative number
// Get the coefficients of the equation from the user
var a = prompt("What is the value of 'a'? \n", "");
var b = prompt("What is the value of 'b'? \n", "");
var c = prompt("What is the value of 'c'? \n", "");
// Compute the square root and denominator of the result
var root_part = Math.sqrt(b * b - 4.0 * a * c);
var denom = 2.0 * a;
// Compute and display the two roots
var root1 = (-b + root_part) / denom;
var root2 = (-b - root_part) / denom;
document.write("The first root is: ", root1, "<br />");
document.write("The second root is: ", root2, "<br />");

2
 Java script reserved words:

 Identifiers: They must begin with a letter, an underscore (_), or a dollar sign ($). Subsequent characters
may be letters, underscores, dollar signs, or digits.
 Comments – two ways: First, whenever two adjacent slashes (//) appear on a line, the rest of the line
is considered a comment. Second, /* may be used to introduce a comment, and */ to terminate it, in
both single- and multiple-line comments.

Primitives, Operations, and Expressions


Primitive Types: JavaScript has five primitive types: Number, String, Boolean, Undefined, and Null.
3
Objects: are closely related to the Number, String, and Boolean types, named Number, String, and
Boolean, respectively. These objects 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 provide properties 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.
Example: Suppose that prim is a primitive variable with the value 17 and obj is a Number object whose
property value is 17.

Numeric: All numeric literals are primitive values of type Number. The Number type values are
represented internally in double-precision floating-point form. Because there is only a single numeric 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 a
possibly signed integer literal. The following are valid numeric literals:

String literals: A string literal is a sequence of zero or more characters delimited by either single quotes (‘)
or double quotes (“).
Example: 'You are the most wonderful person I have ever seen'.
Null: 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 that will cause a runtime error.
Undefined: The only value of type Undefined is undefined. Unlike null, there is no reserved word
undefined. If a variable has been explicitly declared, but not assigned a value, it has the value undefined. If
the value of an undefined variable is displayed, the word undefined is displayed.
Boolean: The only values of type Boolean are true and false. These values are usually computed as the
result of evaluating a relational or Boolean expression.

Declaring Variables

4
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 declaration statement 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:

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.
Example:
For a=7: (++a) * 3 = 24 and (a++) * 3 = 21
Precedence and associativity of the numeric operators:

Example:

Parentheses can be used to force any desired precedence. For example, the addition will be done before
the multiplication in the following expression: (a + b) * c
The Math Object

5
The Math object provides a collection of properties of Number objects 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. All of the Math
methods are referenced through the Math object, as in Math.sin(x).

The Number Object


The Number object includes a collection of useful properties that have constant values. 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 point number, such as a number that is too large (an overflow),
returns the value “not a number,” which is displayed as NaN. To determine whether a variable has the NaN
value, the predefined predicate function 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 it is called to a string.

The String Catenation Operator


String catenation is specified with the operator denoted by a plus sign (+). For example, if the value of first is
"Freddie", the value of the following expression:
first + " Freeloader"
is "Freddie Freeloader".

Implicit Type Conversions


The JavaScript interpreter performs several different implicit type conversions. Such conversions are called
coercions. In general, when a value of one type is used in a position 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.
If either operand of a + operator is a string, the operator is interpreted as a string catenation operator. If the
other operand is not a string, it is coerced to a string.
For example, consider the following expression: "August" + 1977
6
In this expression, because the left operand is a string, the operator is considered to be a catenation operator.
This forces string context on the right operand, so the right operand is implicitly converted to a string.
Therefore, the expression evaluates to "August 1997".

Explicit Type Conversions


There are several different ways to force type conversions, primarily between strings and numbers. Strings
that contain numbers can be converted to numbers with the String constructor, as in the following statement:
var str_value = String(value);

This conversion can also be done with the toString method, which has the advantage that it can be given a
parameter to specify the base of the resulting number.

var num = 6;
var str_value = num.toString();
var str_value_binary = num.toString(2);

In the first conversion, the result is "6"; in the second, it is "110".

A number also can be converted to a string by catenating it with the empty string.
Strings can be explicitly converted to numbers in several different ways. One way is with the Number
constructor, as in the following statement:
var number = Number(aString);
The same conversion could be specified by subtracting zero from the string, as in the following statement:
var number = aString - 0;

String Properties and Methods


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.
The number of characters in a string is stored in the length property as follows:
var str = "George";
var len = str.length;
In this code, len is set to the number of characters in str, namely, 6. In the expression str.length, str is a
primitive variable, but we treated it as if it were an object (referencing one of its properties). In fact, when str
is used with the length property, JavaScript implicitly builds a temporary String object with a property whose
value is that of the primitive variable. After the second statement is executed, the temporary String object is
discarded.

String methods

7
Note that, for the String methods, character positions start at zero. For example, suppose str has been defined
as follows:
var str = "George";
Then the following expressions have the values shown:
str.charAt(2) is 'o'
str.indexOf('r') is 3
str.substring(2, 4) is 'org'
str.toLowerCase() is 'george'

The typeof Operator


The 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".

Assignment Statements
There is a simple assignment operator, 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;

The Date Object


A Date object is created with the new operator and the Date constructor, which has several forms. Simplest
Date constructor, takes no parameters and builds an object with the current date and time for its properties.
For example,
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 Mean Time.

Methods for the Date object:

8
Screen Output and Keyboard Input
The Document object has several properties and methods.
 The method, write, is used to create output, which is dynamically created HTML document content.
This content is specified in the parameter of write.

For example, if the value of the variable result is 42,

document.write("The result is: ", result, "<br />");


produces the following output:

 The alert method opens a dialog window and displays its parameter in that window. It also displays an
OK button.
Example of an alert: consider the following code, in which we assume that the value of sum is 42.

alert("The sum is:" + sum + "\n");

9
 The confirm method opens a dialog window in which the method 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.

var question =
confirm("Do you want to continue this download?");

 The prompt method creates a dialog window that contains a text box used to collect a string of input
from the user, which prompt returns as its value. Tthis 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 buttons.

name = prompt("What is your name?", "");

alert, prompt, and confirm cause the browser to wait for a user response. In the case of alert, the OK
button must be pressed for the JavaScript interpreter to continue. The prompt and confirm methods
wait for either OK or Cancel to be pressed.

Control Statements
A compound statement in JavaScript is a sequence of statements delimited by braces. A control
construct is a control statement together with the statement or compound statement whose execution
it controls.

Control Expressions
The expressions upon which statement flow control can be based include primitive values, relational
expressions, and compound expressions.
The result of evaluating a control expression is one of the Boolean values true and false. If the value of
a

10
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).
If the special value, NaN, is interpreted as a Boolean, it is false. If undefined 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 has the value 0.
A relational expression has two operands and one relational operator. Table lists the relational
operators.

JavaScript has operators for the AND, OR, and NOT Boolean operations. These are && (AND), || (OR),
and ! (NOT).
Operator precedence and associativity:

Selection Statements
The selection statements are (if-then and if-then-else).

11
The switch Statement

Example:
// borders2.js
// An example of a switch statement for table border size selection
var bordersize;
var err = 0;
bordersize = prompt("Select a table border size: " +
"0 (no border), " +
"1 (1 pixel border), " +
"4 (4 pixel border), " +
"8 (8 pixel border), ");
switch (bordersize) {
case "0": document.write("<table>");
break;
case "1": document.write("<table border = '1'>");
break;
case "4": document.write("<table border = '4'>");
break;
case "8": document.write("<table border = '8'>");
break;
default: {
document.write("Error - invalid choice: ",
bordersize, "<br />");
err = 1;
}}
If (err == 0) {
document.write("<caption> 2010 NFL Divisional",
" Winners </caption>");
document.write("<tr>",
"<th />",
"<th> American Conference </th>",
"<th> National Conference </th>",
"</tr>",
"<tr>",
"<th> East </th>",
"<td> New England Patriots </td>",
"<td> Philadelphia Eagles </td>",
"</tr>",
"<tr>",

12
"<th> North </th>",
"<td> Pittsburgh Steelers </td>",
"<td> Chicago Bears </td>",
"</tr>",
"<tr>",
"<th> West </th>",
"<td> Kansas City Chiefs </td>",
"<td> Seattle Seahawks </td>",
"</tr>",
"<tr>",
"<th> South </th>",
"<td> Indianapolis Colts </td>",
"<td> Atlanta Falcons </td>",
"</tr>",
"</table>");

Loop Statements
While statement:

For statement:

Do-while statement:

13
Example: Date object and a simple for loop

// date.js
// Illustrates the use of the Date object by
// displaying the parts of a current date and
// using two Date objects to time a calculation
// Get the current date
var today = new Date();
// Fetch the various parts of the date
var dateString = today.toLocaleString();
var day = today.getDay();
var month = today.getMonth();
var year = today.getFullYear();
var timeMilliseconds = today.getTime();
var hour = today.getHours();
var minute = today.getMinutes();
var second = today.getSeconds();
var millisecond = today.getMilliseconds();
// Display the parts
document.write(
"Date: " + dateString + "<br />",
"Day: " + day + "<br />",
"Month: " + month + "<br />",
"Year: " + year + "<br />",
"Time in milliseconds: " + timeMilliseconds + "<br />",
"Hour: " + hour + "<br />",
"Minute: " + minute + "<br />",
"Second: " + second + "<br />",
"Millisecond: " + millisecond + "<br />");
// Time a loop
var dum1 = 1.00149265, product = 1;
var start = new Date();
for (var count = 0; count < 10000; count++)
product = product + 1.000002 * dum1 / 1.00001;
var end = new Date();
var diff = end.getTime() - start.getTime();
document.write("<br />The loop took " + diff + " milliseconds <br />");

14
Object Creation and Modification
The following statement creates an object that has no properties:
var my_object = new Object();
In this case, the constructor called is that of Object, which endows the new object with no properties,
although it does have access to some inherited methods. The variable my_object references the new object.
Calls to constructors must include parentheses, even if there are no parameters.
The properties of an object can be accessed with 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 just the names of values.
They are used with object variables to access property values. Because properties are not variables, they are
never declared.
The number of members of a class in Java or C++ 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’s name. Consider the following
example:
// Create an Object object
var my_car = new Object();
// Create and initialize the make property
my_car.make = "Ford";
// Create and initialize model
my_car.model = "Fusion";
This code creates a new object, my_car, with two properties: make and model.
There is an abbreviated way to create an object and its properties. For example, the object referenced with
my_car in the previous example could be created with the following statement:
var my_car = {make: "Ford", model: "Fusion"};
Notice that this statement includes neither the new operator nor the call to the Object constructor.

Because objects can be nested, you can create a new object that is a property of my_car with properties of its
own, as in the following statements:

15
my_car.engine = new Object();
my_car.engine.config = "V6";
my_car.engine.hp = 263;

Properties can be accessed in two ways. First, any property can be accessed in the same way it is assigned a
value, namely, with the object-dot-property notation. Second, the property names of an object can be
accessed as if they were elements of an array. To do so, the property name (as a string literal) is used as a
subscript.
For example, after execution of the statements

var prop1 = my_car.make;


var prop2 = my_car["make"];

the variables prop1 and prop2 both have the value "Ford".
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 the following example:
delete my_car.model;
JavaScript has a loop statement, for-in, that is perfect for listing the properties of an object. The form of for-in
is
for (identifier in object)
statement or compound statement
Consider the following example:
for (var prop in my_car)
document.write("Name: ", prop, "; Value: ",
my_car[prop], "<br />");
In this example, the variable, prop, takes on the values of the properties of the my_car object, one for each
iteration. So, this code lists all of the values of the properties of my_car.

Arrays
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 a constructor. In the case of arrays, the constructor is
named Array:
var my_list = new Array(1, 2, "three", "four");
var your_list = new Array(100);
In the first declaration, an Array object of length 4 is created and initialized. Notice that the elements of an
array need not have the same type. In the second declaration, 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.

16
The second way to create an Array object is with a literal array value, which is a list of values enclosed in
brackets:
var my_list_2 = [1, 2, "three", "four"];
The array my_list_2 has the same values as the Array object my_list created previously with new.

Characteristics of Array Objects


The lowest index of every JavaScript array is zero. Access to the elements of an array is specified with numeric
subscript expressions placed in brackets. The length of an array is the highest subscript to which a value has
been assigned, plus 1. For example, if my_list is an array with four elements and the following statement is
executed, the new length of my_list will be 48.
my_list[47] = 2222;
The length of an array is both read and write accessible through the length property, which is created for
every array object by the Array constructor. Consequently, the length of an array can be set to whatever you
like by assigning the length property, as in the following example:
my_list.length = 1002;
Now, the length of my_list 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).
Only the assigned elements of an array actually occupy space. For example, if it is convenient to use the
subscript range of 100 to 150 (rather than 0 to 99), an array of length 151 can be created. But if only the
elements indexed 100 to 150 are assigned values, the array will require the space of 51 elements, not 151. The
length property of an array is not necessarily the number of elements allocated. For example, the following
statement sets the length property of new_list to 1002, but new_list may have no elements that have values
or occupy space:
new_list.length = 1002;
To support JavaScript’s dynamic arrays, all array elements are allocated dynamically from the heap. Assigning
a value to an array element that did not previously exist creates that element.
// insert_names.js
// This script has an array of names, name_list,
// whose values are in alphabetical order. New
// names are input through a prompt. Each new
// name is inserted into the name_list array,
// after which the new list is displayed.
// The original list of names
var name_list = new Array("Al", "Betty", "Kasper","Michael", "Roberto",
"Zimbo");
var new_name, index, last;
// Loop to get a new name and insert it
while (new_name =
prompt("Please type a new name", "")) {
17
last = name_list.length - 1;
// Loop to find the place for the new name
while (last >= 0 && name_list[last] > new_name) {
name_list[last + 1] = name_list[last];
last--;
}
// Insert the new name into its spot in the array
name_list[last + 1] = new_name;
// Display the new array
document.write("<p><strong>The new name list is:</strong> ","<br />");
for (index = 0; index < name_list.length; index++)
document.write(name_list[index], "<br />");
document.write("</p>");
} //** end of the outer while loop

Array Methods
Array objects have a collection of useful methods. The join method converts all of the elements of an array to
strings and 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:
var names = new Array["Mary", "Murray", "Murphy", "Max"];
. . .
var name_string = names.join(" : ");

The value of name_string is now "Mary : Murray : Murphy : Max". 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 become strings if they are not already strings and sorts
them alphabetically. For example, consider the following statement:
names.sort();
The value of names is now ["Mary", "Max", "Murphy", "Murray"].
The concat method catenates its actual parameters to the end of the Array object on which it is called.
Consider the following statements:
var names = new Array["Mary", "Murray", "Murphy", "Max"];
. . .
var new_names = names.concat("Moo", "Meow");

The new_names array now has length 6, with the elements of names, along with "Moo" and "Meow", as its
fifth and sixth elements.
The slice method does for arrays what the substring method does for strings, returning the part of the Array
object specified by its parameters, which are used as subscripts. The array returned 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, consider the following statements:
18
var list = [2, 4, 6, 8, 10];
. . .
var list2 = list.slice(1, 3);

The value of list2 is now [4, 6]. If slice is given just one parameter, the array that is returned has all of the
elements of the object, starting with the specified index. In the following statements
var list = ["Bill", "Will", "Jill", "dill"];
. . .
var listette = list.slice(2);

the value of listette is set to ["Jill", "dill"].


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, separated by commas. So, for Array objects, the toString
method behaves much like join.
The push, pop, unshift, and shift methods of Array allow the easy implementation of stacks and queues in
arrays. The pop and push methods respectively remove and add an element to the high end of an array, as in
the following statements:
var list = ["Dasher", "Dancer", "Donner", "Blitzen"];
var deer = list.pop(); // deer is "Blitzen"
list.push("Blitzen");

// This puts "Blitzen" back on list


The shift and unshift methods respectively remove and add an element to the beginning of an array. For
example, assume that list is created as before, and consider the following statements:
var deer = list.shift(); // deer is now "Dasher"
list.unshift("Dasher"); // This puts "Dasher" back on list

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 literals, as shown in the script nested_arrays.js:
// nested_arrays.js
// An example illustrating an array of arrays
// Create an array object with three arrays as its elements
var nested_array = [[2, 4, 6], [1, 3, 5], [10, 20, 30]];
// Display the elements of nested_list
for (var row = 0; row <= 2; row++) {
document.write("Row ", row, ": ");
for (var col = 0; col <=2; col++)
document.write(nested_array[row][col], " ");
document.write("<br />");
}

19
Functions
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 body of 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. The
parentheses 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 returned to 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 is executed 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 a return 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 returns undefined 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 an assignment
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 to other variables, and be the elements of an
array. The following example is illustrative:
function fun() { document.write(
"This surely is fun! <br/>");}
ref_fun = fun; // Now, ref_fun refers to the fun object
fun(); // A call to fun
ref_fun(); // Also a call to fun

Because JavaScript functions are objects, their references can be properties in other objects, in which case
they act as methods.

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 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 that are implicitly declared have global scope—that is, they
are visible in the entire HTML document (or entire file if the script is in its own file)—even if the implicit
20
declaration occurs within a function definition. Variables that are explicitly declared outside function
definitions also have global scope. As stated earlier, we recommend that all variables be explicitly declared.
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 explicitly declared with var in the
body of a function has local scope.
If a variable that is defined both as a local variable and as a global variable appears in a function, 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.

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 calls to the
function, are called formal 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 like local variables. Because references are passed as the actual parameters of objects, the
called function has access to the objects and can change them, thereby providing the semantics of pass-by-
reference parameters. However, if a reference to an object is passed to a function and the function changes its
corresponding formal parameter (rather than the object to which it points), then the change has no effect on
the actual parameter. For example, suppose an array is passed as a parameter to a function, as in the
following code:
function fun1(my_list) {
var list2 = new Array(1, 3, 5);
my_list[3] = 14;
. . .
my_list = list2;
. . .
}
. . .
var list = new Array(2, 4, 6, 8)
fun1(list);

The first assignment to my_list in fun1 changes the object to which my_list refers, which was created in the
calling code. However, the second assignment to my_list changes it to refer to a different array object. This
does not change the actual parameter in the caller.
Because of JavaScript’s dynamic typing, there is no type checking of parameters. The called function itself can
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 checked 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.
All parameters are communicated through a property array, arguments, that, like other array objects, has a
property named length. By accessing arguments.length, a function can determine the number of actual
21
parameters that were passed. Because the arguments array is directly accessible, 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). The following example
illustrates a variable number of function parameters:
// params.js
// The params function and a test driver for it.
// This example illustrates a variable number of
// function parameters
// Function params
// Parameters: A variable number of parameters
// Returns: nothing
// Displays its parameters
function params(a, b) {
document.write("Function params was passed ",
arguments.length, " parameter(s) <br />");
document.write("Parameter values are: <br />");
for (var arg = 0; arg < arguments.length; arg++)
document.write(arguments[arg], "<br />");
document.write("<br />");
}
// A test driver for function params
params("Mozart");
params("Mozart", "Beethoven");
params("Mozart", "Beethoven", "Tchaikowsky");

There is no elegant way in JavaScript to pass a primitive value by reference. One inelegant way is to put the
value in an array and pass the array, as in the following script:

// Function by10
// Parameter: a number, passed as the first element
// of an array
// Returns: nothing
// Effect: multiplies the parameter by 10
function by10(a) {
a[0] *= 10;
}
. . .
var x;
var listx = new Array(1);
. . .

22
listx[0] = x;
by10(listx);
x = listx[0];

This approach works because arrays are objects.


Another way to have a function change the value of a primitive-type actual parameter is to have the function
return the new value as follows:

function by10_2(a) {
return 10 * a;
}
. . .
var x;
. . .
x = by10_2(x);

The sort Method


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 numbers, simply subtracting the second from the first produces the required result. For example, if you
want to use the sort method to sort the array of numbers num_list into descending order, you could do so
with the following code:

// Function num_order
// Parameter: Two numbers
// Returns: If the first parameter belongs before the
// second in descending order, a negative number
// If the two parameters are equal, 0
// If the two parameters must be
// interchanged, a positive number
function num_order(a, b) {return b - a;}
// Sort the array of numbers, list, into
// ascending order
num_list.sort(num_order);
Example:
The following example of an HTML document contains a JavaScript function to compute the median of an
array of numbers. The function first uses the sort method to sort the array. If the length of the given array is
odd, the median is the middle element and is determined by dividing the length by 2 and truncating the result
with the use of floor. If the length is even, the median is the average of the two middle elements. Note that
round is used to compute the result of the average computation. Here is the code:

// medians.js
// A function and a function tester
// Illustrates array operations
// Function median
// Parameter: An array of numbers
// Result: The median of the array
// Return value: none
function median(list) {
23
list.sort(function (a, b) {return a - b;});
var list_len = list.length;
// Use the modulus operator to determine whether
// the array's length is odd or even
// Use Math.floor to truncate numbers
// Use Math.round to round numbers
if ((list_len % 2) == 1)
return list[Math.floor(list_len / 2)];
else
return Math.round((list[list_len / 2 - 1] +
list[list_len / 2]) / 2);
} // end of function median
// Test driver
var my_list_1 = [8, 3, 9, 1, 4, 7];
var my_list_2 = [10, -2, 0, 5, 3, 1, 7];
var med = median(my_list_1);
document.write("Median of [", my_list_1, "] is: ",
med, "<br />");
med = median(my_list_2);
document.write("Median of [", my_list_2, "] is: ",
med, "<br />");

Constructors

JavaScript constructors are special functions that create and initialize the properties of newly created objects.
Every new expression must include a call to a constructor whose name is the same as that of the object being
created.
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 initialize the
properties of the object. For example, the following constructor:

function car(new_make, new_model, new_year) {


this.make = new_make;
this.model = new_model;
this.year = new_year;
}

could be used as in the following statement:


my_car = new car("Ford", "Fusion", "2012");

So far, we have considered only data properties. If a method is to be included in the object, it is initialized the
same way as if it were a data property. For example, suppose you wanted a method for car objects that listed
the property values. A function that could serve as such a method could be written as follows:
24
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 line must then be added to the car constructor:

this.display = display_car;

Now the call my_car.display() will produce the following output:


Car make: Ford
Car model: Fusion
Car year: 2012

The collection of objects created by using the same constructor is related to the concept of class in an object-
oriented programming language. All such objects have the same set of properties and methods, at least
initially. These objects can diverge from each other through user code changes. Furthermore, there is no
convenient way to determine in the script whether two objects have the same set of properties and methods.

Pattern Matching by Using Regular Expressions


The simplest pattern-matching method is search, which takes a pattern as a parameter. The search method
returns the position in the String object (through which it is called) at which the pattern matched. If there is no
match, search returns –1. Most characters are normal, which means that, in a pattern, they match themselves.
The position of the first character in the string is 0. As an example, consider the following statements:

var str = "Rabbits are furry";


var position = str.search(/bits/);
if (position >= 0)
document.write("'bits' appears in position", position,
"<br />");
else
document.write("'bits' does not appear in str <br />");
These statements produce the following output:
'bits' appears in position 3

Character and Character-Class Patterns


The “normal” characters are those that are not metacharacters. Metacharacters are characters that have
special meanings in some contexts in patterns. The following are the pattern metacharacters:
\|()[]{}^$*+?.
Metacharacters can themselves be matched by being immediately preceded by a backslash .

A period matches any character except newline. So, the following pattern matches "snowy",
"snowe", and "snowd", among others:
/snow./

25
To match a period in a string, the period must be preceded by a backslash in the pattern. For
example, the pattern /3\.4/ matches 3.4. The pattern / 3.4/ matches 3.4 and 374, among
others.
It is often convenient to be able to specify classes of characters rather than individual
characters. Such classes are defined by placing the desired characters in brackets. Dashes can
appear in character class definitions, making it easy to specify sequences of characters. For
example, the following character class matches 'a', 'b', or 'c':
[abc]
The following character class matches any lowercase letter from 'a' to 'h':
[a-h]
If a circumflex character (^) is the first character in a class, it inverts the specified set. For
example, the following character class matches any character except the letters 'a', 'e', 'i', 'o',
and 'u':
[^aeiou]
Because they are frequently used, some character classes are predefined and named and can
be specified by their names. These are shown in Table, which gives the names of the classes,
their literal definitions as character classes, and descriptions of what they match.

The following examples show patterns that use predefined character classes:

/\d\.\d\d/ // Matches a digit, followed by a period,


// followed by two digits
/\D\d\D/ // Matches a single digit
/\w\w\w/ // Matches three adjacent word characters

In many cases, it is convenient to be able to repeat a part of a pattern, often a character or character class. To
repeat a pattern, a numeric quantifier, delimited by braces, is attached. For example, the following pattern
matches

26
xyyyyz:
/xy{4}z/

There are also three symbolic quantifiers: asterisk (*), plus (+), and question mark (?). An asterisk means zero
or more repetitions, a plus sign means one or more repetitions, and a question mark means one or none. For
example, the following pattern matches strings that begin with any number of x’s (including zero), followed by
one or more y’s, possibly followed by z:

/x*y+z?/

The quantifiers are often used with the predefined character-class names, as in the following pattern, which
matches a string of one or more digits followed by a decimal point and possibly more digits:
/\d+\.\d*/

As another example, the pattern


/[A-Za-z]\w*/

matches the identifiers (a letter, followed by zero or more letters, digits, or underscores) in some
programming languages.
There is one additional named pattern that is often useful: \b (boundary), which matches the boundary
position between a word character (\w) and a nonword character (\W), in either order. For example, the
following pattern matches

"A tulip is a flower" but not "A frog isn't":


/\bis\b/

The pattern does not match the second string because the “is” is followed by another word character (n).
The boundary pattern is different from the named character classes in that it does not match a character;
instead, it matches a position between two characters.

Anchors
It is useful to be able to specify that a pattern must match at a particular position in a string. The most
common example of this type of specification is requiring a pattern to match at one specific end of the string.
A pattern is tied to a string position with an anchor. A pattern can be specified to match only at the beginning
of the string by preceding it with a circumflex (^) anchor. For example, the following pattern matches "pearls
are pretty" but does not match "My pearls are pretty":

/^pearl/

A pattern can be specified to match at the end of a string only by following the pattern with a dollar sign
anchor. For example, the following pattern matches "I like gold" but does not match "golden":

/gold$/

Anchor characters are like boundary-named patterns: They do not match specific characters in the string;
rather, they match positions before, between, or after characters.

27
Pattern Modifiers
Modifiers can be attached to patterns to change how they are used, thereby increasing their flexibility. The
modifiers are specified as letters just after the right delimiter of the pattern. The i modifier makes the letters
in the pattern match either uppercase or lowercase letters in the string.
For example, the pattern
/Apple/i matches ‘APPLE’, ‘apple’, ‘APPle’, and any other combination of uppercase and lowercase spellings of
the word “apple.”
The x modifier allows white space to appear in the pattern. Because comments are considered white space,
this provides a way to include explanatory comments in the pattern.
For example, the pattern

/\d+ # The street number


\s # The space before the street name
[A-Z][a-z]+ # The street name
/x

is equivalent to

/\d+\s[A-Z][a-z]+/

Other Pattern-Matching Methods of String

The replace method is used to replace substrings of the String object that match the given pattern. 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 predefined
variables $1, $2, and so on. For example, consider the following statements:

var str = "Fred, Freddie, and Frederica were siblings";


str.replace(/Fre/g, "Boy");

In this example, str is set to "Boyd, Boyddie, and Boyderica were siblings", and $1, $2, and $3 are all set to
"Fre".

The match method is the most general of the String pattern-matching methods. The match method takes a
single parameter: a 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 the g modifier, 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:

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].

Now consider a pattern that has parenthesized subexpressions:


var str = "I have 428 dollars, but I need 500";
var matches = str.match(/(\d+)([^\d]+)(\d+)/);
28
document.write(matches, "<br />");

The following is the value of the matches array after this code is interpreted:
["428 dollars, but I need 500", "428"," dollars, but I need ", "500"]

In this result array, the first element, "428 dollars, but I need 500", is the match; the second, third, and fourth
elements are the parts of the string that matched the parenthesized parts of the pattern, (\d+), ([^\d]+), and
(\d+).

The split method of String splits its object string into substrings on the basis of a given string or pattern. The
substrings are returned in an array. For example, consider the following code:

var str = "grapes:apples:oranges";


var fruit = str.split(":");

In this example, fruit is set to [grapes, apples, oranges].

Example:
// forms_check.js
// A function tst_phone_num is defined and tested.
// This function checks the validity of phone
// number input from a form
// Function tst_phone_num
// Parameter: A string
// Result: Returns true if the parameter has the form of a valid
// seven-digit phone number (3 digits, a dash, 4 digits)
function tst_phone_num(num) {
// Use a simple pattern to check the number of digits and the dash
var ok = num.search(/^\d{3}-\d{4}$/);
if (ok == 0)
return true;
else
return false;
} // end of function tst_phone_num
// A script to test tst_phone_num
var tst = tst_phone_num("444-5432");
if (tst)
document.write("444-5432 is a valid phone number <br />");
else
document.write("Error in tst_phone_num <br />");
tst = tst_phone_num("444-r432");
if (tst)
document.write("Program error <br />");
else
document.write(
"444-r432 is not a valid phone number <br />");
tst = tst_phone_num("44-1234");
if (tst)
document.write("Program error <br />");
29
else
document.write("44-1234 is not a valid phone number <br /");

Errors in Scripts
The JavaScript interpreter is capable of detecting various errors in scripts. These are primarily syntax errors,
although uses of undefined variables are also detected.

Debugging a script is a bit different from debugging a program in a more typical programming language,
mostly because errors that are detected by the JavaScript interpreter are found while the browser is
attempting to display a document. In some cases, a script error causes the browser not to display the
document and does not produce an error message. Without a diagnostic message, you must simply examine
the code to find the problem. For example, consider the following sample script:
// debugdemo.js
// An example to illustrate debugging help
var row;
row = 0;
while(row != 4 {
document.write("row is ", row, "<br />");
row++;
}
Notice the syntax error in the while statement (a missing right parenthesis). Figure shows the browser display
of what happens when an attempt is made to run debugdemo.js.

Write JavaScript scripts for the problems that follow. Write an HTML file that references the JavaScript file.

1. Output: A table of the numbers from 5 to 15 and their squares and cubes, using alert.

<!DOCTYPE html>
<!-- e4_1.html - A solution to Exercise 4.1
-->
<html lang = "en">
<head>
<title> Exercise 4.1 </title>
<meta charset = "utf-8" />
</head>
<body>
30
<script type = "text/javascript">
<!--
var number, square, cube;
document.write("Number, Square, Cube <br /><br />");
for (number = 5; number < 16; number++) {
square = number * number;
cube = number * square;
document.write(number + "…………" + square + "…………" + cube + "<br />");
}
// -->
</script>
</body>
</html>

2. Output: The first 20 Fibonacci numbers, which are defined as in the sequence 1, 1, 2, 3, . . . where each number in the
sequence after the second is the sum of the two previous numbers. You must use document.write to produce the output.

<!DOCTYPE html>
<!-- e4_2.html - A solution to Exercise 4.2
-->
<html lang = "en">
<head>
<title> Exercise 4.2 </title>
<meta charset = "utf-8" />
</head>
<body>
<script type = "text/javascript">
<!--
var first = 1, second = 1, next, count;
document.write("First 20 Fibonacci Numbers <br/><br/>");
document.write("1 - 1 <br/> 2 - 1 <br/>");
for (count = 3; count <= 20; count++) {
next = first + second;
document.write(count + " - " + next + "<br/>");
first = second;
second = next;
}
// -->
</script>
</body>
</html>

31
3. Modify the script of Question 2 to use prompt to input a number n that is the number of the Fibonacci number required
as output.

<!DOCTYPE html>
<!-- e4_4.html - A solution to Exercise 4.4
-->
<html lang = "en">
<head>
<title> Exercise 4.4 </title>
<meta charset = "utf-8" />
</head>
<body>
<script type = "text/javascript">
<!--
var first = 1, second = 1, next, count;
number = prompt("How many Fibonacci numbers do you want? (3-50)", "");
if (number >= 3 && number <= 50) {
document.write("First " + number + " Fibonacci Numbers <br /><br />");
document.write("1 - 1 <br/> 2 - 1 <br />");

for (count = 3; count <= number; count++) {


next = first + second;
document.write(count + " - " + next + "<br />");
first = second;
second = next;
}
}
else
document.write("Error - number not in the range 3-50");
// -->
</script>
</body>
</html>

32
4. Input: A line of text, using prompt.
Output: The words of the input text, in alphabetical order.

<!DOCTYPE html>
<!-- e4_6.html - A solution to Exercise 4.6
-->
<html lang = "en">
<head>
<title> Exercise 4.6 </title>
<meta charset = "utf-8" />
</head>
<body>
<script type = "text/javascript">
<!--
var first = 1, second = 1, next, count;

str = prompt("Please input your sentence", "");


var words = str.split(" ");
words = words.sort();
words_len = words.length;
for (count = 0; count < words_len; count++)
document.write(words[count] + "<br/>");
// -->
</script>
</body>
</html>

33
5. Modify the script of Question 4 to get a second input from the user, which is either "ascending" or "descending". Use
this input to determine how to sort the input words.

<!DOCTYPE html>
<!-- e4_7.html - A solution to Exercise 4.7
-->
<html lang = "en">
<head>
<title> Exercise 4.7 </title>
<meta charset = "utf-8" />
<script type = "text/javascript">
<!--
// A function to compare strings for reverse alphabetic order

function dec_order(a, b) {
if (a > b)
return -1;
else if (a < b)
return 1;
else return 0;
}
// -->
</script>
</head>

<body>
<script type = "text/javascript">
<!--
var order, str, words, word_len, count;
// Get the input
str = prompt("Please input your sentence", "");
order = prompt("What order? (ascending or descending)", "");
// If the order is recognized, issue an error message
if (order != "descending" && order != "ascending")
document.write("Error - order is incorrectly specified <br/>");
// Otherwise, do the sort, depending on the requested order
else {
var words = str.split(" ");
if (order == "ascending")
words = words.sort();
else
words = words.sort(dec_order);
// Write out the results
words_len = words.length;
for (count = 0; count < words_len; count++)
document.write(words[count] + "<br/>");
}
// -->
</script>
</body>
</html>

34
6. Function: e_names
Parameter: An array of names, represented as strings.
Returns: The number of names in the given array that end in either "ie" or "y".
<!DOCTYPE html>
<!-- e4_9.html - A solution to Exercise 4.9
-->
<html lang = "en">
<head>
<title> Exercise 4.9 </title>
<meta charset = "utf-8" />
<script type = "text/javascript">
<!--
// Function e_names
// Parameter: an array of strings
// Returns: the number of given strings that end
// in either "ie" or "y"

function e_names(names) {
var len, index, count = 0;
len = names.length;

// Loop to use pattern matching to produce the count

for (index = 0; index < len; index++) {


position1 = names[index].search(/ie$/);
position2 = names[index].search(/y$/);
if (position1 + position2 > -2)
count++;
}
return count;
}
// -->
</script>
</head>
35
<body>
<script type = "text/javascript">
<!--
// Function e_names tester

var new_names = new Array ("freddie", "bob", "mieke", "yahoo2", "georgey");


result = e_names(new_names);
document.write("The number of special names is: " + result + "<br/>");
// -->
</script>
</body>
</html>

7. Function: reverser
Parameter: A number.
Returns: The number with its digits in reverse order.

<?xml version = "1.0" encoding = "utf-8"?>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- e4_14.html - A solution to Exercise 4.14


-->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title> Exercise 4.14 </title>
<meta charset = "utf-8" />
<script type = "text/javascript">
<!--
var result;

// Function reverser
// Parameter: a number
// Returns: the number with its digits in reverse order
// Note: Math.floor must be used to get the integer part
// of the division operations

function reverser(num) {
var digit, position = 0;

// If the number has just one digit, that's it


if (num < 10)
return num;
// Get the first digit
result = num % 10;
num = Math.floor(num / 10);
// Loop to produce the result for the rest
do {
digit = num % 10;
result = 10 * result + digit;
num = Math.floor(num / 10);
} while (num >= 1);
return result;

36
}
// -->
</script>
</head>

<body>
<script type = "text/javascript">
<!--
// Function reverser tester
var num1 = 2468, num2 = 7;
result = reverser(num1);
document.write("The reverse of 2468 is: " + result + "<br />");
result = reverser(num2);
document.write("The reverse of 7 is: " + result + "<br />");
// -->
</script>
</body>
</html>

37
Event Handling
 Detect certain activities of the browser and the browser user and provide computation when those
activities occur. These computations are specified with a special form of programming called event-
driven programming.
 In event-driven programming, parts of the program are executed at completely unpredictable times,
often triggered by user interactions with the program that is executing.
 An event is a notification that something specific has occurred, either in the browser, such as the
completion of the loading of a document, or a browser user action, such as a mouse click on a form
button. Strictly speaking, an event is an object that is implicitly created by the browser and the
JavaScript system in response to something having happened.
 An event handler is a script that is implicitly executed in response to the appearance of an event. Event
handlers enable a Web document to be responsive to browser and user activities. One of the most
common uses of event handlers is to check for simple errors and omissions in user input to the elements
of a form, either when they are changed or when the form is submitted. This kind of checking saves the
time of sending incorrect form data to the server.
 Events are created by activities associated with specific HTML elements. For example, the click event
can be caused by the browser user clicking a radio button or the link of an anchor tag, among other
things.
 The process of connecting an event handler to an event is called registration. There are two distinct
approaches to event handler registration, one that assigns tag attributes and one that assigns handler
addresses to object properties.

Events and their tag attributes

38
An HTML element is said to get focus when the user puts the mouse cursor over it and clicks the left mouse button. An element can
also get focus when the user tabs to the element. When a text element has focus, any keyboard input goes into that element.
Obviously, only one text element can have focus at one time. An element becomes blurred when the user moves the cursor away from
the element and clicks the left mouse button or when the user tabs away from the element. An element obviously becomes blurred
when another element gets focus. Several nontext elements can also have focus, but the condition is less useful in those cases.

Event attributes and their tags

39
<input type = "button" id = "myButton" onclick = "alert('You clicked my button!');" />

In many cases, the handler consists of more than a single statement. In these cases, often a function is used and the literal string value
of the attribute is the call to the function.

Consider the following example of a button element:


<input type = "button" id = "myButton" onclick = "myButtonHandler();" />

40
An event handler function could also be registered by assigning its name to the associated event property on the button object, as in
the following example:

document.getElementById("myButton").onclick = myButtonHandler;

Handling Events from Body Elements


onload attribute of <body> to specify the event handler:

HTML:
<!DOCTYPE html>
<!-- load.html
A document for load.js
-->
<html lang = "en">
<head>
<title> load.html </title>
<meta charset = "utf-8" />
<script type = "text/javascript" src = "load.js" >
</script>
</head>
<body onload="load_greeting();">
<p />
</body>
</html>

Js file:
// load.js
// An example to illustrate the load event
// The onload event handler
function load_greeting () {
alert("You are visiting the home page of \n" +
"Pete's Pickled Peppers \n" + "WELCOME!!!");
}

Handling Events from Button Elements


This example presents a set of radio buttons that enables the user to select information about a specific airplane.
The click event is used in this example to trigger a call to alert, which presents a brief description of the selected
airplane. The calls to the event handlers send the value of the pressed radio button to the handler. This is another
way the handler can determine which of a group of radio buttons is pressed.
HTML:
<!DOCTYPE html>
<!-- radio_click.hmtl
A document for radio_click.js
Creates four radio buttons that call the planeChoice
event handler to display descriptions
-->
<html lang = "en">
41
<head>
<title> radio_click.html </title>
<meta charset = "utf-8" />
<script type = "text/javascript" src = "radio_click.js" >
</script>
</head>
<body>
<h4> Cessna single-engine airplane descriptions </h4>
<form id = "myForm" action = "">
<p>
<label> <input type = "radio" name = "planeButton"
value = "152"
onclick = "planeChoice(152)" />
Model 152 </label>
<br />
<label> <input type = "radio" name = "planeButton"
value = "172"
onclick = "planeChoice(172)" />
Model 172 (Skyhawk) </label>
<br />
<label> <input type = "radio" name = "planeButton"
value = "182"
onclick = "planeChoice(182)" />
Model 182 (Skylane) </label>
<br />
<label> <input type = "radio" name = "planeButton"
value = "210"
onclick = "planeChoice(210)" />
Model 210 (Centurian) </label>
</p>
</form>
</body>
</html>

JS FILE:
// radio_click.js
// An example of the use of the click event with radio buttons,
// registering the event handler by assignment to the button
// attributes
// The event handler for a radio button collection
function planeChoice (plane) {
// Produce an alert message about the chosen airplane
switch (plane) {
case 152:
alert("A small two-place airplane for flight training");
break;
case 172:
alert("The smaller of two four-place airplanes");
break;
case 182:
alert("The larger of two four-place airplanes");
break;
case 210:
alert("A six-place high-performance airplane");
break;
default:
alert("Error in JavaScript function planeChoice");
break;
}
}

42
Handling Events from Text Box and Password Elements
Text boxes and passwords can create four different events: blur, focus, change, and select.

HTML file:
<!DOCTYPE html>
<!-- nochange.html
A document for nochange.js
-->
<html lang = "en">
<head>
<title> nochange.html </title>
<meta charset = "utf-8" />
<script type = "text/javascript" src = "nochange.js" >
</script>
<style type = "text/css">
td, th, table {border: thin solid black}
</style>
</head>
<body>
<form action = "">
<h3> Coffee Order Form </h3>
<!-- A bordered table for item orders -->
<table>
<!-- First, the column headings -->
<tr>
<th> Product Name </th>
<th> Price </th>
<th> Quantity </th>
</tr>
<!-- Now, the table data entries -->
<tr>
<th> French Vanilla (1 lb.) </th>
<td> $3.49 </td>
<td> <input type = "text" id = "french"
size ="2" /> </td>
</tr>
<tr>
<th> Hazlenut Cream (1 lb.) </th>
<td> $3.95 </td>
43
<td> <input type = "text" id = "hazlenut"
size = "2" /> </td>
</tr>
<tr>
<th> Colombian (1 lb.) </th>
<td> $4.59 </td>
<td> <input type = "text" id = "colombian"
size = "2" /></td>
</tr>
</table>
<!-- Button for precomputation of the total cost -->
<p>
<input type = "button" value = "Total Cost"
onclick = "computeCost();" />
<input type = "text" size = "5" id = "cost"
onfocus = "this.blur();" />
</p>
<!-- The submit and reset buttons -->
<p>
<input type = "submit" value = "Submit Order" />
<input type = "reset" value = "Clear Order Form" />
</p>
</form>
</body>
</html>

JS file: event handler


// nochange.js
// This script illustrates using the focus event
// to prevent the user from changing a text field
// The event handler function to compute the cost
function computeCost() {
var french = document.getElementById("french").value;
var hazlenut = document.getElementById("hazlenut").value;
var colombian = document.getElementById("colombian").value;
// Compute the cost
document.getElementById("cost").value =
totalCost = french * 3.49 + hazlenut * 3.95 +
colombian * 4.59;
} //* end of computeCost

Validating Form Input


HTML:
<!DOCTYPE html>
<!-- pswd_chk.html
A document for pswd_chk.ps
Creates two text boxes for passwords
-->
<html lang = "en">
44
<head>
<title> Illustrate password checking> </title>
<meta charset = "utf-8" />
<script type = "text/javascript" src = "pswd_chk.js" >
</script>
</head>
<body>
<h3> Password Input </h3>
<form id = "myForm" action = "" >
<p>
<label> Your password
<input type = "password" id = "initial"
size = "10" />
</label>
<br /><br />
<label> Verify password
<input type = "password" id = "second"
size = "10" />
</label>
<br /><br />
<input type = "reset" name = "reset" />
<input type = "submit" name = "submit" />
</p>
</form>
<!-- Script for registering the event handlers -->
<script type = "text/javascript" src = "pswd_chkr.js">
</script>
</body>
</html>

JS file:event handler
// pswd_chk.js
// An example of input password checking using the submit
// event
// The event handler function for password checking
function chkPasswords() {
var init = document.getElementById("initial");
var sec = document.getElementById("second");
if (init.value == "") {
alert("You did not enter a password \n" +
"Please enter one now");
return false;
}
if (init.value != sec.value) {
alert("The two passwords you entered are not the same \n" +
"Please re-enter both now");
return false;
} else
return true;
}

JS file:event registration
// pswd_chkr.js
// Register the event handlers for pswd_chk.html
document.getElementById("second").onblur = chkPasswords;
document.getElementById("myForm").onsubmit = chkPasswords;

45
Error:

Check validity of the form


HTML:
<!DOCTYPE html>
<!-- validator.html
A document for validator.js
Creates text boxes for a name and a phone number
-->
<html lang = "en">
<head>
<title> Illustrate form input validation> </title>
<meta charset = "utf-8" />
<script type = "text/javascript" src = "validator.js" >
</script>
</head>
<body>
<h3> Customer Information </h3>
<form action = "">
<p>
<label>
<input type = "text" id = "custName" />
Name (last name, first name, middle initial)
</label>
<br /><br />
<label>
<input type = "text" id = "phone" />
Phone number (ddd-ddd-dddd)
</label>
<br /><br />
<input type = "reset" id = "reset" />
<input type = "submit" id = "submit" />
</p>
</form>
<script type = "text/javascript" src = "validatorr.js">
</script>
</body>
</html>

JS file: event handler


// validator.js
// An example of input validation using the change and submit
// events
// The event handler function for the name text box

46
function chkName() {
var myName = document.getElementById("custName");
// Test the format of the input name
// Allow the spaces after the commas to be optional
// Allow the period after the initial to be optional
var pos = myName.value.search(
/^[A-Z][a-z]+, ?[A-Z][a-z]+, ?[A-Z]\.?$/);
if (pos != 0) {
alert("The name you entered (" + myName.value +
") is not in the correct form. \n" +
"The correct form is:" +
"last-name, first-name, middle-initial \n" +
"Please go back and fix your name");
return false;
} else
return true;
}
// The event handler function for the phone number text box
function chkPhone() {
var myPhone = document.getElementById("phone");
// Test the format of the input phone number
var pos = myPhone.value.search(/^\d{3}-\d{3}-\d{4}$/);
if (pos != 0) {
alert("The phone number you entered (" + myPhone.value +
") is not in the correct form. \n" +
"The correct form is: ddd-ddd-dddd \n" +
"Please go back and fix your phone number");
return false;
} else
return true;
}
JS file: event registration
// validatorr.js
// Register the event handlers for validator.html
document.getElementById("custName").onchange = chkName;
document.getElementById("phone").onchange = chkPhone;

Error:

Error:

47
1. The document must display an image and three buttons. The buttons should be labeled simply 1, 2, and 3.
When pressed, each button should change the content of the image to that of a different image.
<html>
<head>
</head>
<body>
<!--On button click changeImg() will be call-->
<input type="button" onclick="changeImg(1)" value="1"/>
<input type="button" onclick="changeImg(2)" value="2"/>
<input type="button" onclick="changeImg(3)" value="3"/><br><br>
<img id="photo" src="b.jpg" width="300" height="200"/>
</body>
<script>
// if x ==1 than image one will be display
function changeImg(x)
{ if(x==1)
{
document.getElementById("photo").src="b.jpg";
}
else if(x==2) // if x ==2 than image Second will be display
{
document.getElementById("photo").src="c.jpg";
}
else // if x ==3 than image third will be display
{
document.getElementById("photo").src="d.jpg";
}
}
</script>
</html>

2. Example to find length of string:


<!DOCTYPE html>
<html>
<head>
<title> Exercise to find length of string</title>
</head>
<body>
<script type="text/javascript">
<!--
var str="Bangalore";
48
var len=str.length;
document.write("Length of string \"Bangalore\" is :" ,len,"<br />");
//-->
</script>
</body>
</html>

3. Example for charAt() function:


<!DOCTYPE html>
<html>
<head>
<title> Exercise for charAt function of
string</title>
</head>
<body>
<script type="text/javascript">
<!--
var you=prompt("Enter your name:", " ");
document.write("The character at position in your name is :" , you.charAt(4));
//-->
</script>
</body>
</html>

4. Example for substr and substring functions:

<!DOCTYPE html>
<html>
<head>
<title> Exercise for substr and substring functions of string</title>
</head>
<body>
<script type="text/javascript">
49
<!--
var str="Bangalore";
document.write("substr function on string Bangalore (1,4) is: "+str.substr(1,4)+"<br />");
document.write("substring function on string Bangalore (1,4) is: "+str.substring(1,4));
//-->
</script>
</body>
</html>

5. Example for split function:


<!DOCTYPE html>
<html>
<head>
<title> Exercise for split function of string</title>
</head>
<body>
<script type="text/javascript">
<!--
var str="Bangalore one today";
document.write("split function on string Bangalore one today with Blank as separator is: "+str.split(" ") +"<br
/>");
document.write("split function on string Bangalore one today is: "+str.split(""));
//--></script>
</body>
</html>

6. Example for alert, confirm and prompt:

50
7. JavaScript script to find Largest of three numbers

<!DOCTYPE html>
<html> <body>
<script type="text/javascript">
{
var n1=Number(prompt("Enter number 1: "));
var n2=Number(prompt("Enter number 2: "));
var n3=Number(prompt("Enter number 3: "));
if (n1>n2 && n1>n3)
alert(n1+" is largest");
else if(n2>n3)
alert(n2+" is largest");
else
alert(n3+" is largest");
}
</script>
</body>
</html>

8. Example of switch case:


<!DOCTYPE html>
<html>
<body>
<script>
var day=4;
var dayName;
switch(day)
{
case 1:dayName='Sunday'; break;
case 2:dayName='Monday'; break;
case 3:dayName='Tuesday'; break;
case 4:dayName='Wednesday'; break;
case 5:dayName='Thursday'; break;
case 6:dayName='Friday'; break;
case 7:dayName='Saturday'; break;
default:
dayName='Invalid day';
}
51
document.write(dayName);
</script>
</body>
</html>

9. Program to find the number of negative values, zeros and values greater than Zeros in the given array.
<body>
<script type="text/javascript">
var list = [2, 10, -4, 0, 8,-6,0, 21];
var i,pos=0,neg=0,zeros=0;
document.write("Elements of Array","<br />");
for(i=0;i<list.length;i++)
document.write(list[i]+" ");
document.write("<br /><br />");
for(i=0;i<list.length;i++) {
if(Number(list[i])>0)
pos++;
else if(Number(list[i])<0)
neg++;
else
zeros++;
}
document.write("Number of Positive Numbers:",pos,"<br / >");
document.write("Number of Negative Numbers: ",neg,"<br / >");
document.write("Number of Zeros: ",zeros,"<br / >");
</script>
</body>

10. Example of join method:


<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The Join method</h2>
<p>The Join method helps to join two arrays as a string:</p>
<p id="demo"></p>
<script>
// Original Array
52
var courses = ["HTML", "CSS", "JavaScript", "React"];
// Joining the array elements
document.write(courses.join('|'));
</script>
</body>
</html>

11. Example of slice method:


<!DOCTYPE html>
<html><body>
<h1>JavaScript Arrays</h1>
<h2>The Slice method</h2>
<p>The slice() method returns a new array containing a portion of the original array, based on the start and
end index provided as arguments:</p>
<p id="demo"></p>
<script>
// Original Array
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Case 1: Extract the first 3 elements of the array


const case1 = arr.slice(0, 3);
document.write("Case 1: First 3 Array Elements: ", case1 ,"<br />");

// Case 2: Extract the last 3 array elements


const case2 = arr.slice(-3);
document.write("Case 2: Last 3 Array Elements: ", case2,"<br />");

// Case 3: Extract elements from middle of array


const case3 = arr.slice(3, 7);
document.write("Case 3: Extract elements from middle: ", case3,"<br />");

// Case 4: Start index is greater than end index


const case4 = arr.slice(5, 2);
document.write("Case 4: Start index is greater than end index: ", case4,"<br />");

// Case 5: Negative start index


const case5 = arr.slice(-4, 9);
document.write("Case 5: Negative start index: ", case5,"<br />");

// Case 6: Negative end index

53
const case6 = arr.slice(3, -2);
document.write("Case 6: Negative end index: ", case6,"<br />");

// Case 7: Only start index is provided


const case7 = arr.slice(5);
document.write("Case 7: Only start index is provided: ", case7,"<br />");

// Case 8: Start index and end index are out of range


const case8 = arr.slice(15, 20);
document.write("Case 8: Start and end index out of range: ", case8,"<br />");

// Case 9: Start and end index are negative and out of range
const case9 = arr.slice(-15, -10);
document.write("Case 9: Start and end index are negative" + " and out of range: ", case9);
</script>
</body>
</html>

12. Example of push method:


<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The Push method</h2>
<p>The Push method is used to add one or more elements to the end of an array:</p>
<p id="demo"></p>
<script>
var languages = ["JavaScript", "Python", "Java", "Lua"];
var count = languages.push("C++");
document.write(languages,"<br />"); // [ 'JavaScript', 'Python', 'Java', 'Lua', 'C++' ]
</script>
</body>
</html>

54
13. Example for function:
<html>
<head>
</head>
<body>
<script type="text/javascript">
var a,b,c;
a=10; b=20;
//actual parameters a and b
c=sum(a,b);
document.write("Total :",c);

//formal parameters x and y


function sum(x,y)
{
var z=x+y;
return z;
}
</script>
</body>
</html>

14. Write JavaScript function which accepts input from user a string and prints the position of the leftmost
vowel (first vowel).
<html> <head></head ><body> <script type="text/javascript">
//function to print the position of the leftmost vowel in the string
function firstvowel(){
var find = 0,pos,i; var str=prompt("Enter the string: ");
str=str.toLowerCase();
for(i=0;i<str.length;i++)
{
if(str[i]=='a' || str[i]=='e' || str[i]=='i' || str[i]=='o' || str[i]=='u')
{
55
find=1; pos=i; break;
}
}
if(find)
document.write("Position of first vowel in the string ", str, " was ",(pos+1));
else
document.write("Vowel Not found");
return;
}
document.write("Function to find first vowel in a String","<br />");
firstvowel(); </script> </body> </html>

15. Write a program check validity of the USN of the format 1BM19IS followed by three digits.
Example:
Valid: 1BM19IS065, 1bm19is999
Not Valid: 1BM18IS6 , 1BM17IS038, 1is16BM065
Note: Accept the USN from the user through textbox.

<html>
<head>
<script type="text/javascript">
function validate() {
strValidate=strForm.str.value.search(/1BM19IS[0-9]{3}/i);
if(strValidate== -1) {
alert("Not Valid");
} else
alert("Valid"); }
</script> </head>

<body>
<form name="strForm" onsubmit="validate();">
<label> <b> Enter USN </b> </label>
<input type="text" name="str"/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>

56
16. Write a Regular Expression to validate ten digit mobile number
Example:
Valid: 8762742909, 9448444160
Not Valid: 84441604, 762742909

<html>
<head>
<script type="text/javascript">
function validate() {
strValidate=strForm.str.value.search(/[0-9]{10}/);
if(strValidate== -1) {
alert("Not Valid");
}
alert("Valid");
}
</script>
</head>
<body>
<form name="strForm" onsubmit="validate();">
<label> <b> Enter Mobile Number </b> </label>
<input type="text" name="str"/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>

57

You might also like