JavaScript
Dr. Awad Khalil
Computer Science Department
AUC
JavaScript, by Dr. Khalil
1
Content
Introduction
 Uses of JavaScript
 Incorporating JavaScript in Documents
 Basic JavaScript Syntax
 Datatypes & Variables
 JavaScript Arithmetic operators
 JavaScript Assignment operators
 JavaScript Comparison Operators
 JavaScript Logical Operators
 JavaScript string Operators & Tokens
 Control Structures

JavaScript, by Dr. Khalil
2
Introduction
 JavaScript
scripting language, is a technology which
facilitates a disciplined approach to designing computer
programs that enhance the functionality and appearance
of Web pages.
 JavaScript
was originally created by Netscape in 1996,
while Microsoft’s version of JavaScript is called Jscript.
 Despite
its naming, JavaScript is not Java. It inherited
the moniker “Java” due to many similarities with Sun’s
Java language.
JavaScript, by Dr. Khalil
3
Uses for JavaScript
 It
is a client-based language.
 It
is a scripting language with definite limitations.
 Data
verification: JavaScript can parse form data prior
to the data being submitted to the server, ensuring that
there are no obvious errors (missing or improperly
formatted data).
 Document
animation and automation: Accessing
element data and properties via the DOM, JavaScript
can affect changes in elements’ content, appearance,
size, position, and so forth.
 Basic
Document Intelligence: JavaScript can initiate
changes in documents based on other dynamic criteria..
JavaScript, by Dr. Khalil
4
Incorporating JavaScrip in Documents

The most popular method of incorporating JavaScript in
documents is by enclosing the scripts within <script> tags with
the following syntax:
<script type=“MIME_type>
…. Script content ….
</script>

Current versions of XHTML support the following Multipurpose
Internet Mail Extensions (MIME) types for the <script> tag:






text/ecmascript
text/javascript
text/jscript
text/vbscript
text/vbs
text/xml
JavaScript, by Dr. Khalil
5
Optional Attributes in <script> tag
Attribute
Value(s)
Use
charset
charset
code
Defines the character encoding
used in the script
defer
defer
Informs the user agent that the
script will not generate content,
and document processing
(rendering) can continue
without waiting to evaluate the
script content.
src
URL
Instructs the user agent to
incorporate the contents of the
document found at the specified
URL as the script content.
JavaScript, by Dr. Khalil
6
Placement of the Script Tag
 Technically,
the script tag should be placed within the
<head> section of the document where it can be easily
located.
 However,
in practice we can place the <script> tag
anywhere within the document.
 That
said, the <script> tag should always appear within
a block element.
JavaScript, by Dr. Khalil
7
Execution of Scripts
Unless otherwise instructed, user agents
execute JavaScript code as soon as it is
encountered in a document. The
exceptions to this rule include the
following
 Scripting being disabled in the user
agent.
 The defer attribute being set in the
<script> tag.
 All code being contained within
functions that are not explicitly
called during the document’s
rendering.
 We can force a script to run
immediately after the document is
loaded by using the onload event in the
<body> tag:
<body onload=“ScriptFunctionName”>

<html> <head>
<script type=“text/javascript”>
function runmelater() {
// script code
}
</script>
</head>
<body>
<p>
<script type=“text/javascript”>
// script code (not enclosed in
function(s))
</script>
</p>
</body>
<html>
JavaScript, by Dr. Khalil
8
Basic JavaScript Syntax
JavaScript follows fairly basic syntax that can be outlined with a
few simple rules:

All
code should appear within appropriate constructs, namely
between <script> tags or within event attributes.
With
few exceptions, code lines should end with a semicolon
(;). Notable exceptions to this rule are lines that end in a block
delimiter ({ or }).
Blocks
of code (usually under control structures such as
functions, if statements, and so on) are enclosed in braces ({ and
}).
Although
it is not absolutely necessary, explicit declaration of
all variables is a good idea.
The
use of functions to delimit code fragments is
recommended.
Comments
can be inserted in JavaScript code by prefixing the
comment with a double-slash
(//) or surrounded the comment
JavaScript, by Dr. Khalil
with /* and */ pairs
9
Data Types and Variables

JavaScript, like most other programming languages, supports a wide range of
data types. However, JavaScript employs little data type checking. JavaScript
supports the following data types:
 Booleans
 Integers
 Floating –point numbers
 Strings
 Arrays

Examples:
a = new Array();
months = new (“JAN”, “FEB”, “MAR, “APR”, “MAY, “JUN”, “JUL”, …,
“DEC”);
s = new String ();
n = new Number ();
JavaScript, by Dr. Khalil
10
Variables




JavaScript variables are
case sensitive and can
contain a mix of letters
and numbers.
JavaScript uses the var
statement to explicitly
declare variables,
Examples:
var x;
var x = 20;
var x = 20, Lastname
= ‘Khalil’;
JavaScript variables have
global scope unless they
are declared within a
function.

For example, in the
following code the variable
x is global while variable y
is local to the function:
<script
type=“text/javascript”>
var x = 100;
function spacefill(text,
amount) {
var y = 0;
…
}
</script>
JavaScript, by Dr. Khalil
11
Simple Examples – First Program in JavaScript
<HTML>
<HEAD>
<TITLE>A First Program in JavaScript</TITLE>
<SCRIPT LANGUAGE=“JavaScript”>
document.writeln(“<H1>Welcome to JavaScript
Programming!</H1>”);
</SCRIPT>
</HEAD><BODY></BODY>
</HTML>
JavaScript, by Dr. Khalil
12
Example 2 – Printing on one line
<HTML>
<HEAD>
<TITLE>A First Program in JavaScript</TITLE>
<SCRIPT>
document.write( “<FONT COLOR=‘red’><H1>Welcome to “
document.writeln(“JavaScript Programming!</H1></FONT>”);
</SCRIPT>
</HEAD><BODY></BODY>
</HTML>
JavaScript, by Dr. Khalil
13
Example 3 – Printing on multiple lines
<HTML>
<HEAD>
<TITLE>Printing Multiple Lines</TITLE>
<SCRIPT LANGUAGE=“JavaScript”>
document.writeln(“<H1>Welcome to <BR>JavaScript<BR>
Programming!</H1>”);
</SCRIPT>
</HEAD><BODY></BODY>
</HTML>
JavaScript, by Dr. Khalil
14
Example 4 – Displaying multiple lines in a dialog box
<HTML>
<HEAD>
<TITLE>Printing Multiple Lines</TITLE>
<SCRIPT LANGUAGE=“JavaScript”>
window.alert(“Welcome to\nJavaScript\nProgramming!”);
</SCRIPT>
</HEAD><BODY></BODY>
</HTML>
JavaScript, by Dr. Khalil
15
JavaScript Arithmetic Operators
Operator
+
*
/
%
++
--
Use
Addition
Subtraction
Multiplication
Division
Modulus
Increment
Decrement
JavaScript, by Dr. Khalil
16
JavaScript Assignment Operators
Operator
=
+=
-=
*=
/=
%=
Use
Assignment
Increment assignment
Decrement assignment
Multiplication assignment
Division assignment
Modulus assignment
JavaScript, by Dr. Khalil
17
Assignment Operators
Assignment
Operator
Initial
variable
Value
Sample
Explanation ASSIGNS
expression
+=
c=3
c += 7
c=c+7
10 to c
-=
d=5
d -= 4
d=d–4
1 to d
*=
e=4
e *= 5
e=e*5
20 to e
/=
f=6
f /= 3
f=f/3
2 to f
%=
g = 12
g %= 9
g=g%9
3 to g
JavaScript, by Dr. Khalil
18
Example 5 – Adding Integers
<HTML>
<HEAD>
<TITLE>An Addition Program</TITLE>
<SCRIPT LANGUAGE=“JavaScript”>
var firstNumber,
// first string entered by user
secondNumber,
// second string entered by user
number1,
// first number to add
number2,
// second number to add
sum;
// sum of number1 and number2
// read in first number from user as string
firstNumber = window.prompt( “Enter first integer”, “0’ );
// read in second number from user as string
secondNumber = window.prompt( “Enter second integer”, “0’ );
// convert numbers from strings to integers
number1 = parseInt(firstNumber);
number2 = parseInt(secondNumber);
// add the numbers
sum = number1 + number2;
// display the results
document.writeln( “<H1>The sum is “ + sum + “</H1>”);
</SCRIPT>
</HEAD><BODY></BODY>
</HTML>
JavaScript, by Dr. Khalil
19
Example 5 – Adding Integers
JavaScript, by Dr. Khalil
20
JavaScript Comparison Operators
Operator
==
===
!=
>
<
>=
<=
Use
Is equal to
Exactly equal to – in value and type
Is not equal to
Is greater than
Is less than
Is greater than or equal to
Is less than or equal to
JavaScript, by Dr. Khalil
21
JavaScript Logical Operators
Operator
Use
&&
││
!
And
Or
Not
JavaScript, by Dr. Khalil
22
Demonstrating the Logical Operators
<HTML><HEAD><TITLE>Demonstrating the logical operators</TITLE>
<SCRIPT LANGUAGE="JavaScript">
document.writeln( "<TABLE BORDER='10' WIDTH='100%'>" );
document.writeln(
"<TR><TD WIDTH= '25%'>Logical AND (&&)</TD>" +
"<TD>false && false: " + ( false && false ) +
"<BR>false && true: " + ( false && true ) +
"<BR>true && false: " + ( true && false ) +
"<BR>true && true: " + ( true && true ) + "</TD>" );
document.writeln(
"<TR><TD WIDTH= '25%'>Logical OR (||)</TD>" +
"<TD>false || false: " + ( false || false ) +
"<BR>false || true: " + ( false || true ) +
"<BR>true || false: " + ( true || false ) +
"<BR>true || true: " + ( true || true ) + "</TD>" );
document.writeln(
"<TR><TD WIDTH= '25%'>Logical NOT (!)</TD>" +
"<TD>!false: " + ( !false ) +
"<BR>!true: " + ( !true ) + "</TD>" );
doccument.writeln( "</TABLE>" );
</SCRIPT>
</HEAD><BODY></BODY>
</HTML>
JavaScript, by Dr. Khalil
23
JavaScript, by Dr. Khalil
24
JavaScript String Operators
Operator
+
Use
Concatenation
JavaScript, by Dr. Khalil
25
JavaScript String Tokens
Token
Character
\\
\’
Backslash
Single quote
\”
\b
\f
\n
\r
\t
\v
Double quote
Backspace
Form Feed
Line Feed
Carriage Return
Horizontal Tab
Vertical Tab
JavaScript, by Dr. Khalil
26
Control Structures
if structure
if ( <condition> ) {
// statement(s) to execute if condition is true
} [ else {
// statement(s) to execute if condition is false
}]
JavaScript, by Dr. Khalil
27
Control Structures (Cont’d)
if structure
if ( studentGrade >= 60 )
document.writeln ( “Passed” );
If else structure
if ( studentGrade >= 60 )
document.writeln ( “Passed” );
else
document.writeln ( “Failed” );
--------------------------------------------------------------------------------------------------if ( studentGrade >= 60 )
document.writeln ( “Passed” );
else {
document.writeln ( “Failed<BR>” );
document.writeln ( “You must repeat this course” );
}
JavaScript, by Dr. Khalil
28
Control Structures (Cont’d)
Nested-if structure
if ( studentGrade >= 90 )
document.writeln ( “A” );
else
if ( studentGrade >= 80 )
document.writeln ( “B” );
else
if ( studentGrade >= 70 )
document.writeln ( “C” );
else
if ( studentGrade >= 60 )
document.writeln ( “D” );
else
document.writeln ( “F” );
JavaScript, by Dr. Khalil
29
Control Structures
switch structure
switch ( gradeLetter ) {
case “A”:
case “a”:
gradeName = “Excellent;
break;
case “B”:
case “b”:
gradeName = “Very Good”;
break;
case “C”:
case “c”:
gradeName = “Good”;
break;
case “D”:
case “d”:
gradeName = “Sufficient”;
break;
case “F”:
case “f”:
gradeName = “Fail”;
break;
default:
gradeName = “Invalid grade”;
}
JavaScript, by Dr. Khalil
30
Decision Making – An Example
<HTML>
<HEAD>
<TITLE>Performing Comparisons</TITLE>
<SCRIPT LANGUAGE=“JavaScript”>
var first,
// first string entered by user
second,
// second string entered by user
// read in first number from user as string
first = window.prompt( “Enter first integer:”, “0’ );
// read in second number from user as string
second = window.prompt( “Enter second integer:”, “0’ );
document.writeln( “<H1>Comparison Results</H1>” );
document.writeln( “<TABLE BORDER = ‘1’ WIDTH = ‘100%’>” );
if ( first == second )
document.writeln( “<TR><TD>” + first + “ == “ + second + “</TD></TR>” );
if ( first != second )
document.writeln( “<TR><TD>” + first + “ != “ + second + “</TD></TR>” );
if ( first > second )
document.writeln( “<TR><TD>” + first + “ > “ + second + “</TD></TR>” );
if ( first >= second )
document.writeln( “<TR><TD>” + first + “ >= “ + second + “</TD></TR>” );
if ( first < second )
document.writeln( “<TR><TD>” + first + “ < “ + second + “</TD></TR>” );
if ( first <= second )
document.writeln( “<TR><TD>” + first + “ >= “ + second + “</TD></TR>” );
document.writeln( “</TABLE>” );
</SCRIPT>
</HEAD><BODY></BODY>
</HTML>
JavaScript, by Dr. Khalil
31
JavaScript, by Dr. Khalil
32
JavaScript, by Dr. Khalil
33
Repetition Structures – while Loop
while
while ( <condition> ) {
// statement(s) to execute
};
Examples
var product = 2;
while ( product <= 100 )
product = product * 2;
------------------------------var counter = 1
while ( counter <= 30 )
{
sum = sum + score;
counter = counter + 1;
}
---------------------------------JavaScript, by Dr. Khalil
34
Repetition - Counter-controlled while loop
<HTML>
<HEAD>
<TITLE>Counter-controlled loops</TITLE>
<SCRIPT LANGUAGE="JavaScript">
var counter = 1; // initialize the counter
while ( counter <= 7 ) // loop condition
{
document.writeln( "<p><FONT SIZE = '" + counter + "'>HTML font
size " +
counter + "</FONT></p>" );
++counter;
// increment
}
</SCRIPT>
</HEAD><BODY></BODY>
</HTML>
JavaScript, by Dr. Khalil
35
JavaScript, by Dr. Khalil
36
Counter-controlled loop – An Example
<HTML><HEAD><TITLE>Class Average Program</TITLE>
<SCRIPT LANGUAGE="JavaScript">
var total,
// sum of grades
gradeCounter, // number of grades entered
gradeValue,
// grade value
average,
// average of all grades
grade;
// grade typed by uesr
// initialization phase
total = 0;
// clear total
gradeCounter = 1; // initialize the counter
// processing phase
while ( gradeCounter <= 10 ) {
grade = window.prompt ( "Enter integer grade:", "0" );
gradeValue = parseInt( grade );
total = total + gradeValue;
gradeCounter = gradeCounter + 1;
}
average = total / 10;
document.writeln( "<H1>Class average is " + average + "</H1>" );
</SCRIPT>
</HEAD><BODY>Refresh to run the script again</BODY>
</HTML>
JavaScript, by Dr. Khalil
37
JavaScript, by Dr. Khalil
38
Repetition Structures – do while Loop
Examples
do while
do {
// statement(s) to execute
X = 0;
do {
x++; // increment x
} while (x < 20);
}While ( <condition> );
JavaScript, by Dr. Khalil
39
The do/while loop
<HTML>
<HEAD>
<TITLE>Using the do/while loop</TITLE>
<SCRIPT LANGUAGE="JavaScript">
var counter = 1;
do {
document.writeln( "<H" + counter + ">This is an H" + counter + " level head" + "</H" +
counter + ">" );
++ counter;
} while ( counter <= 6 );
</SCRIPT>
</HEAD><BODY></BODY>
</HTML>
JavaScript, by Dr. Khalil
40
for loop
General Format:
for ( initialization; loopContinuationTest; increment )
statement
--------------------------------------------------------------------------------------------------------------<HTML>
<HEAD>
<TITLE>Counter-controlled loops</TITLE>
<SCRIPT LANGUAGE="JavaScript">
// Initialization, loop condition and incrementing
// are all included in the for structure header.
for ( var counter = 1; counter <= 7; ++counter )
document.writeln( "<p><FONT SIZE = '" + counter + "'>HTML font size " +
counter + "</FONT></p>" );
</SCRIPT>
</HEAD><BODY></BODY>
</HTML>
JavaScript, by Dr. Khalil
41
JavaScript, by Dr. Khalil
42
Sentinel-controlled loop
<HTML><HEAD><TITLE>Class Average Program</TITLE>
<SCRIPT LANGUAGE="JavaScript">
var total,
// sum of grades
gradeCounter,
// number of grades entered
gradeValue,
// grade value
average,
// average of all grades
grade;
// grade typed by uesr
// initialization phase
total = 0;
// clear total
gradeCounter = 0;
// initialize the counter
// processing phase
// prompt for input and read grade from user
grade = window.prompt ( "Enter integer grade, -1 to Quit:", "0" );
gradeValue = parseInt( grade );
while ( gradeValue != -1 ) {
total = total + gradeValue;
gradeCounter = gradeCounter + 1;
grade = window.prompt ( "Enter integer grade, -1 to Quit:", "0" );
gradeValue = parseInt( grade );
}
if ( gradeCounter != 0 ) {
average = total / gradeCounter;
document.writeln( "<H1>Class average is " + average + "</H1>" );
}
else
document.writeln( "<p>No grades were entered!!" );
</SCRIPT>
</HEAD><BODY>Refresh to run the script again</BODY>
</HTML>
JavaScript, by Dr. Khalil
43
JavaScript, by Dr. Khalil
44
Calculating Compound Interest with for loop
<HTML><HEAD><TITLE>Calculating Compound Interest</TITLE>
<SCRIPT LANGUAGE="JavaScript">
var amount, principal = 1000, rate = 0.1;
document.writeln( "<TABLE BORDER='100' WIDTH='100%'>" );
document.writeln( "<TR><TD WIDTH= '100'><B>Year</B></TD>" );
document.writeln( "<TD><B>Amount on deposit</B></TD></TR>" );
for ( var year = 1; year <= 10; ++year ) {
amount = principal * Math.pow(1.0 + rate, year);
document.writeln( "<TR><TD>" + year + "</TD><TD>" +
Math.round(amount * 100) / 100 + "<TD></TR>" );
}
doccument.writeln( "</TABLE>" );
</SCRIPT>
</HEAD><BODY></BODY>
</HTML>
JavaScript, by Dr. Khalil
45
JavaScript, by Dr. Khalil
46
JavaScript, by Dr. Khalil
47
Break and Continue
var x = 1;
while (x <= 20) {
if (x == 7) continue;
// skip the number 7
// statement(s) to execute if x does not equal 7
}
--------------------------------------------------------------------------------------var y = 1;
while (y <= 20) {
if (x == 100) break;
// if x = 100, leave the loop
// statement(s) to execute
}
// execution continues here when y > 20 or x = 100
--------------------------------------------------------------------------------------JavaScript, by Dr. Khalil
48
Labels
var x = 100;
code_loop:
while (x <= 1000) {
// statement(s)
}
--------------------------------------------------------------------------------------var x = 0, y = 0;
top_loop:
while (x <= 100) {
while (y <= 50) {
……………
if (z == 100) break top_loop;
}
}
// execution resumes here after loops are complete or if z = 100 during the loops execution
-------------------------------------------------------------------------------------------------------------------------
code_block: {
// block of code here
}
JavaScript, by Dr. Khalil
49
Functions









Experience has shown that the best way to develop and maintain a large program is to
construct it from small, simple pieces or modules. This technique is called divide and
conquer.
Modules in JavaScript are called functions. JavaScript programs are written by
combining new functions that the programmer writes with “prepackaged” functions and
objects available in JavaScript.
The “prepackaged” functions that belong to JavaScript objects are often called
methods. The term method implies that the function belongs to a particular object.
The programmer can write programmer-defined functions to define specific tasks that
may be used at many points in a script. The actual statements defining the function are
written only once, and these statements are hidden from other functions.
A function is invoked by a function call. The function call specifies the function name
and provides information (as arguments) that the called function needs to do its task.
Functions allow the programmer to modularize a program.
All variables declared in function definitions are local variables – they are known only
in the function in which they are defined.
Most functions have parameters that provide the means for communicating information
between functions via function calls. A function’s parameters are also considered to be
local variables.
The divide-conquer approach to program development makes program development
more manageable.
JavaScript, by Dr. Khalil
50
Functions



The () represent the function call operator
The return statement passes the result of a function call back to
the calling function.
The format of a function definition is
Function function-name( parameter-list )
{
declarations and statements
}
JavaScript, by Dr. Khalil
51
Built-in Functions
Function
Use
Returns
escape
Creates portable data – typically used to encode
URLs and other information that may include
extended characters (non-alphanumeric). Extended
characters are replaced by their ASCII number
equivalent in hexadecimal %xx form. For
example, a space (ASCII 20) becomes %20.
Encoded version of supplied argument
eval
Parse the supplied string for JavaScript code and
executes the code if found
The value of the last valid statement or
expression encountered in the supplied
argument.
isFinite
Tests an expression or variable to see if it is a valid
number.
True if the supplied argument is a Valid
number, false otherwise.
isNaN
Tests an expression or variable to see if it is not a
((valid) number.
Returns true if the argument is not a number
and false otherwise.
number
Converts an object (typically string data) to a
number.
Returns the supplied argument converted to a
number or the value NaN if the argument
cannot be converted to a valid number.
parseFloat
Parses the given argument for a valid floatingpoint number.
A floating-point representation of the supplied
argument.
parseInt
Parses the given argument for a valid integer
number.
An integer representation of the supplied
argument.
string
Converts the supplied argument to a string
A string representation of the supplied
representation.
argument.
by Dr. Khalil
Converts portable data back into itsJavaScript,
original form.
Decoded version of the supplied argumemt. 52
Unescape
User-Defined Functions

JavaScript supports user-defined functions which allow users to better
organize their code into discrete, reusable chunks. User-defined functions
have the following syntax:
function <function_name> ( <list_of_arguments> ) {
… code of function …
return <value_to_return>;
}
 For example:
function spacefill(text) {
while (text.length < 25) {
text = text + “ “;
}
return text;
}
---------------------------------------------------------------------------------- Elsewhere in your code, you can use this function:
address = spacefill(address);
JavaScript, by Dr. Khalil
53
Example – User-defined Functions
<HTML><HEAD><TITLE>A Programmer-Defined Square Function</TITLE>
<SCRIPT LANGUAGE="JavaScript">
document.writeln( "<H1>Square the numbers from 1 to 10</H1>" );
// square the numbers from 1 to 10
for ( var x = 1; x <= 10; ++x )
document.writeln( "The square of " + x + " is " + square( x ) + "<BR>" );
// square function definition
function square( y )
{
return y * y;
}
</SCRIPT>
</HEAD><BODY></BODY>
</HTML>
JavaScript, by Dr. Khalil
54
JavaScript, by Dr. Khalil
55
<HTML><HEAD><TITLE>A Programmer-Defined maximum Function</TITLE>
<SCRIPT LANGUAGE="JavaScript">
var input1 = window.prompt( "Enter first number", "0" );
var input2 = window.prompt( "Enter second number", "0" );
var input3 = window.prompt( "Enter third number", "0" );
var value1 = parseInt( input1 );
var value2 = parseInt( input2 );
var value3 = parseInt( input3 );
var maxValue = maximum( value1, value2, value3 );
document.writeln( "First number: " + value1 + "<BR>Second number: " + value2 +
"<BR>Third number: " + value3 + "<BR> Maximum is: " +
maxValue );
// maximum function definition
function maximum( x, y, z )
{
return Math.max( x, Math.max( y, z ) );
}
</SCRIPT>
</HEAD><BODY></BODY>
</HTML>
JavaScript, by Dr. Khalil
56
Objects








Objects are a natural way of thinking about the world.
Objects encapsulate data (attributes) and methods (behavior).
Objects have the property of information hiding.
Programs communicate with objects by using well-defined interfaces.
World Wide Web browsers have a set of objects that encapsulate the elements
of an HTML document and expose to a JavaScript programmer attributes and
behaviors that enable a JavaScript program to interact with (or script) the
elements (i.e., objects) in an HTML document.
Math object methods allow programmers to perform many common
mathematical calculations.
An object’s methods are called by writing the name of the object followed by a
dot (.) and the name of the method. In parentheses following the method name
is the argument (or a comma-separated list of arguments) to the method.
String object provides several methods enabling processing String objects.
JavaScript, by Dr. Khalil
57
Built-in Objects



JavaScript is an object-driven language.
“The Document Object Model” – the user
agent – supplies a host of objects that your
scripts can reference.
JavaScript has several built-in objects. For
example, two specific objects exist for
manipulating data: one for performing
math operations (Math) on numeric data
and another for performing operations on
string values (String).
These objects have various methods for
acting upon data:
x = Math.sqrt(x); // square root of x
s = String.toLowerCase(s); // convert s
to lowercase

JavaScript also supports the with statement:
with (Math) {
y = random(200);
x = round (sqrt(y));
}

Another useful object is the Date
object which has several methods
that can be used to manipulate
dates and times in various formats:
<script type=“text/JavaScript”>
months = new Array(“January”,
“February”, “March”, “April”,
“May”, “June”, “July”, “August”,
“September”, “October”,
“November”, “December”);
var today = new Date();
var day = today.getDate();
var month = today.getMonth();
var year = today.getYear();
document.write(months[month]+”
“+day+”, “+year);
</script>
JavaScript, by Dr. Khalil
58
Methods






The Math object’s max method determines the larger of its two
statement values.
The Math object’s random method generates a real value from
0.0 up to (but not including) 1.0.
Math object’s floor rounds its real number argument to the closest
integer not greater than its argument’s value.
The values produced directly by random are always in the range:
0.0 <= Math.random() < 1.0
We can generalize picking a random number from a range of
values by writing:
value = Math.floor( a + Math.random() * b) ;
Where a is the shifting value (the first number in the desired range
of consecutive integers) and b is the scaling factor (the width of
the desired range of consecutive integers).
JavaScript, by Dr. Khalil
59
Math Object’s Methods
Method
Description
Method
Description
abs( x )
Absolute value of x
round( x )
Rounds x to the closest
integer
ceil( x )
Rounds x to the smallest integer
not less than x
sin( x )
Trigonometric sine of x (x
in radians)
cos( x )
Trigonometric cosine of x (x in
radians)
sqrt( x )
Square root of x
exp( x )
Exponential method ex
tan( x )
Trigonometric tangent of x
(x in radians)
floor( x )
Rounds x to the largest integer not
greater than x
log( x )
Natural logarithm of x (base e)
max( x, y ) Larger value of x and y
min( x, y )
Smaller value of x and y
pow( x, y ) X raised to power y (xy)
JavaScript, by Dr. Khalil
60
Random Number Generation
<HTML><HEAD><TITLE>Shifted and Scaled Random Integers</TITLE>
<SCRIPT LANGUAGE="JavaScript">
var value;
document.writeln( "<H1>Random Numbers</H1>" +
"<TABLE BORDER = '5' WIDTH = '50%'><TR>" );
for ( var i = 1; i <= 20; i++ ) {
value = Math.floor( 1 + Math.random() * 6 );
document.writeln( "<TD>" + value + "</TD>" );
if ( i % 5 == 0 && i != 20 )
document.writeln( "</TR><TR>" );
}
document.writeln( "</TR></TABLE>" );
</SCRIPT>
</HEAD><BODY></BODY></HTML>
JavaScript, by Dr. Khalil
61
JavaScript, by Dr. Khalil
62
User-Created Objects
The new declaration statement can be used to create new objects based on existing, builtin objects, for example:

employees = new Array(“Khalil”, “Sameh”, “Sherif”, “Amr”, “Khaled”);
JavaScript also includes built-in constructors for native objects:
function movie (title, genre, releasedate) {
this.title = title;
this.genre = genre;
this.releasedate = releasedate;

}


The constructor can be called as follows:
mov1 = new movie(“Aliens”, Scifi”, “1986-07-18”);
The same object can be created without use of constructor as follows:
mov1 = new object();
move1.title = “Aliens”;
move1.genre = “Scifi”;
move1.releasedate = “1986-07-18”;
JavaScript, by Dr. Khalil
63
Arrays









Arrays are data structures consisting of related data items.
An array is a group of memory locations that all have the same name and are
normally of the same type.
To refer to a particular location or element in the array, specify the name of the
array and the position number (index) of the particular element in the array.
The index (or subscript) must be an integer or an integer expression and the
first element in every array is of index 0.
The length (size) of an array is the number of its elements and is determined by
arrayName.length.
An array in JavaScript is an Array object. Operator new is used to dynamically
allocate the number of elements required by an array. Operator new creates an
object as the program executes, by obtaining enough memory to store an object
of the type specified to the right of new.
The process of creating new objects is also known as creating an instance or
instantiating an object.
An array can be initialized with a comma-separated initializerl ist enclosed in
square brackets [ ].
JavaScript’s for/in control structure enables a script to perform a task for each
element in an array:
for ( var element in arrayName )JavaScript, by Dr. Khalil
64
statement
Arrays – An Example I
<HTML><HEAD><TITLE>Initializing an Array</TITLE>
<SCRIPT LANGUAGE="JavaScript">
// this function is called when the <BODY> element's
// ONLOAD event occurs.
function initializeArrays() {
var n1 = new Array( 5 );
// allocate 5-element Array
var n2 = new Array();
// allocate empty Array
// assign values to each element of Array n1
for ( var i = 0; i < n1.length; ++i )
n1[i] = i * i;
// create and initialize 6 elements in Array n2
for ( i = 0; i < 6; ++i )
n2[i] = 2 * i;
outputArray( "Array n1 contains", n1 );
outputArray( "Array n2 contains", n2 );
}
// output "header" followed by a two-column table
// containing subscripts and elements of "theArray"
function outputArray( header, theArray )
{
document.writeln( "<H2>" + header + "</H2>" );
document.writeln( "<TABLE BORDER='10' WIDTH='100%'>" );
document.writeln( "<TR><TD WIDTH='100'><B>Subscript</B>“ + "<TD><B>Value</B></TR>" );
for ( var i = 0; i < theArray.length; i++ )
document.writeln( "<TR><TD>" + i + "<TD>" + theArray[i] + "</TR>" );
document.writeln( "</TABLE>" );
}
</SCRIPT>
</HEAD>
<BODY ONLOAD = "initializeArrays()">
</BODY>
JavaScript, by Dr. Khalil
</HTML>
65
JavaScript, by Dr. Khalil
66
Arrays – An Example II
<HTML><HEAD><TITLE>Student Poll Program</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function start()
{
var responses = [ 1, 2, 6, 4, 8, 5, 9, 7, 8, 10, 1, 6, 3, 8, 6, 10, 3, 8, 2, 7, 6, 5, 7, 6, 8, 6, 7, 5, 6, 6,
5, 6, 7, 5, 6, 4, 8, 6, 8, 10 ];
var frequency = [ , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ];
for ( var answer in responses )
++frequency[ responses[ answer ] ];
document.writeln( "<TABLE BORDER='10' WIDTH='100%'>" );
document.writeln( "<TR><TD WIDTH='100'><B>Rating</B>"
+ "<TD><B>Frequency</B></TR>" );
for ( var rating = 1; rating < frequency.length; ++rating )
document.writeln( "<TR><TD>" + rating + "<TD>" +
frequency[rating] + "<TR>" );
document.writeln( "</TABLE>" );
}
</SCRIPT>
</HEAD>
<BODY ONLOAD = "start()">
</BODY></HTML>
JavaScript, by Dr. Khalil
67
JavaScript, by Dr. Khalil
68
Event Handling

One of the more powerful anf often used techniques concerning JavaScript is
events. Using event attributes in XHTML tags, such as onmouseover and
onclick, you can create interactive documents that respond to user’s actions.
Event
Trigger
onAbort
Abort selected in browser (stop loading of image or document), usually by
clicking the Stop button
onBlur
When the object loses focus
onChange
When an object is changed (generally a form element)
onClick
When the object is clicked
onDblClick
When the object is double-clicked
onDragDrop
When a object is dropped into the user agent window
onError
When a JavaScript error occurs
onFocus
When an object receives focus
onKeyDown
When the user presses a key
onKeyPress
When the user presses and/or holds down a key
onKeyUp
When the user releases a key
Onload
When the object is loaded into the user agent window (typically used with
the <body> element to run a script when the document has completed
JavaScript, by Dr. Khalil
loading)
69
Event Handling (Cont’d)
Event
Trigger
onMouseDown
When the mouse butoon is depressed
onMouseMove
When the mouse is moved
onMouseOut
When the mouse pointer moves outside the boundary of an object
onMouseOver
When the mouse pointer moves within the boundary of an object
onMouseUp
When the mouse button is released
onMove
When an object (generally a window or frame) is moved
onReset
When the user selects a reset button
onResize
When an object (generally a window or frame) is resized
onSelect
When the user selects text within the object (generally a form element)
onSubmit
When the user selects a submit button
OnUnload
When the object is unloaded from the user agent window (typically used
with the <body> element to run a script when the user navigates away
from a document – a favorite tool of pop-up window coders)
JavaScript, by Dr. Khalil
70
Key Points











The JavaScript language facilitates a disciplined approach to designing computer
programs that enhance Web pages.
Often JavaScripts appear in the <HEAD> section of the HTML document.
The browser interprets the contents of the <HEAD> section first.
The <SCRIPT> tag indicates to the browser that the text that follows is part of a
script. Attribute LANGUAGE specifies the scripting language used in the script –
such as JavaScript.
Every statement should end with a semicolon.
JavaScript is case sensitive.
A string of characters can be contained between the double quotation (“) marks or
single quotation (‘) marks.
A string is sometimes called a character string, a message or string literal.
The browser’s document object represents the HTML document currently being
displayed in the browser. The document object allows a script programmers to specify
HTML text to be displayed in the HTML document.
The browser contains a complete set of objects that allow script programmers every
element of an HTML document.
An object resides in the computer’s memory and contains information used by the
script. The term object normally implies that attributes (data) and behaviors (methods)
are associated with the object. The object’s methods use the attributes to provide
useful services to the client of the object – the script that calls the methods.
JavaScript, by Dr. Khalil
71
Key Points

The document object’s writeln method writes a line of HTML text in the
HTML document.

Unlike writeln, document method write does not position the output
cursor in the HTML document at the beginning of next line of HTML text
after writing its argument.

Each write and writeln statement resumes writing characters where the last
write or writeln stopped writing characters.
Sometimes it is useful to display information in windows called dialog boxes
that “pop up” on the screen to grab the user’s attention. Dialog boxes are
typically used to display important messages to the user who is browsing the
Web page. The browser’s window object displays an alert dialog box with
method alert. Method alert requires as its argument the string to display.
Normally the characters in a string are displayed exactly as they appear
between the double quotes. When a backslash is encountered in a string of
characters, the next character is combined with the backslash to form an
escape sequence. The escape sequence\n is the newline character. It causes
the cursor in the HTML document to move to the beginning of the next line in
the dialog box.


JavaScript, by Dr. Khalil
72
Key Points





The keyword var is used to declare the names of variables. A variable is a
location in the computer’s memory where a value can be stored for use by a
program. Though not required, all variables should be declared with a name in
a var statement before they are used in a program.
A variable name can be any valid identifier. An identifier is a series of
characters consisting of letters, digits, underscores (_) and dollar signs ($) that
does not contain any spaces.
Programmers often indicate the purpose of each variable in the program by
placing a JavaScript comment at the end of each line in the declaration. A
single-line comment begins with the characters // and terminate at the end of
the line. Comments do not cause the browser to perform any action when the
script is interpreted; rather, comments are ignored by the JavaScript
interpreter.
Multiple-line comments begin with delimiter /* and end with delimiter */. All
text between the delimiters of the comment is ignored by the JavaScript
interpreter.
The window object’s prompt method displays a dialog into which the user
can type a value. The first argument is a message (called a prompt) that
directs the user to take a specific action. The optional second argument is the
default string to display in the text field.
JavaScript, by Dr. Khalil
73
Key Points








A variable is assigned a value with an assignment statement using the
assignment operator =. The = operator is called a binary operator because it
has two operands.
Function parseInt converts its string argument to an integer.
JavaScript has a version of the + operator for string concatenation that enables
a string and a value of another data type (including another string) to be
concatenated.
When a value is placed in a memory location, this value replaces the previous
value in that location.
Operators in arithmetic expressions are applied in a precise sequence
determined by the rules of operator precedence.
Parentheses may be used to force the order of evaluation of operators to occur
in any sequence desired by the programmer.
Java’s if structure allows a program to make a decision based on the truth or
falsity of a condition. If the condition is met (the condition is true), the
statement in the body of the if structure is executed. If the condition is not met
(the condition is false), the body statement is not executed.
Conditions in if structures can be formed by using the equality and relational
operators.
JavaScript, by Dr. Khalil
74
Thank you
JavaScript, by Dr. Khalil
75
Descargar

School of Sciences and Engineering