75
JavaScript, by Dr. Khalil 1 JavaScript Dr. Awad Khalil Dr. Awad Khalil Computer Science Department Computer Science Department AUC AUC

JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

Embed Size (px)

Citation preview

Page 1: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 1

JavaScript

Dr. Awad KhalilDr. Awad Khalil

Computer Science DepartmentComputer Science Department

AUCAUC

Page 2: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 2

Content IntroductionIntroduction Uses of JavaScriptUses of JavaScript Incorporating JavaScript in DocumentsIncorporating JavaScript in Documents Basic JavaScript SyntaxBasic JavaScript Syntax Datatypes & VariablesDatatypes & Variables JavaScript Arithmetic operatorsJavaScript Arithmetic operators JavaScript Assignment operatorsJavaScript Assignment operators JavaScript Comparison OperatorsJavaScript Comparison Operators JavaScript Logical OperatorsJavaScript Logical Operators JavaScript string Operators & Tokens JavaScript string Operators & Tokens Control StructuresControl Structures

Page 3: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 3

Introduction

JavaScript scripting language, is a technology which is a technology which facilitates a disciplined approach to designing computer facilitates a disciplined approach to designing computer programs that enhance the functionality and appearance programs that enhance the functionality and appearance of Web pages.of Web pages.

JavaScript was originally created by Netscape in 1996, JavaScript was originally created by Netscape in 1996, while Microsoft’s version of JavaScript is called Jscript.while Microsoft’s version of JavaScript is called Jscript.

Despite its naming, JavaScript is not Java. It inherited Despite its naming, JavaScript is not Java. It inherited the moniker “Java” due to many similarities with Sun’s the moniker “Java” due to many similarities with Sun’s Java language.Java language.

Page 4: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 4

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 JavaScript can parse form data prior

to the data being submitted to the server, ensuring that to the data being submitted to the server, ensuring that there are no obvious errors (missing or improperly there are no obvious errors (missing or improperly formatted data).formatted data).

Document animation and automation: Accessing : Accessing element data and properties via the DOM, JavaScript element data and properties via the DOM, JavaScript can affect changes in elements’ content, appearance, can affect changes in elements’ content, appearance, size, position, and so forth.size, position, and so forth.

Basic Document Intelligence: JavaScript can initiate : JavaScript can initiate changes in documents based on other dynamic criteria..changes in documents based on other dynamic criteria..

Page 5: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 5

Incorporating JavaScrip in Documents

The most popular method of incorporating JavaScript in The most popular method of incorporating JavaScript in documents is by enclosing the scripts within <script> tags with documents is by enclosing the scripts within <script> tags with the following syntax:the following syntax:

<script type=“MIME_type> …. Script content …. </script>

Current versions of XHTML support the following Multipurpose Current versions of XHTML support the following Multipurpose Internet Mail Extensions (MIME) types for the <script> tag:Internet Mail Extensions (MIME) types for the <script> tag: text/ecmascripttext/ecmascript text/javascripttext/javascript text/jscripttext/jscript text/vbscripttext/vbscript text/vbstext/vbs text/xmltext/xml

Page 6: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 6

Optional Attributes in <script> tag

Attribute Value(s) Use

charsetcharset charset charset codecode

Defines the character encoding Defines the character encoding used in the scriptused in the script

deferdefer deferdefer Informs the user agent that the Informs the user agent that the script will not generate content, script will not generate content, and document processing and document processing (rendering) can continue (rendering) can continue without waiting to evaluate the without waiting to evaluate the script content.script content.

srcsrc URLURL Instructs the user agent to Instructs the user agent to incorporate the contents of the incorporate the contents of the document found at the specified document found at the specified URL as the script content.URL as the script content.

Page 7: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 7

Placement of the Script Tag

Technically, the script tag should be placed within the Technically, the script tag should be placed within the <head> section of the document where it can be easily <head> section of the document where it can be easily located.located.

However, in practice we can place the <script> tag However, in practice we can place the <script> tag anywhere within the document.anywhere within the document.

That said, the <script> tag should always appear within That said, the <script> tag should always appear within a block element.a block element.

Page 8: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 8

Execution of Scripts Unless otherwise instructed, user agents Unless otherwise instructed, user agents

execute JavaScript code as soon as it is execute JavaScript code as soon as it is encountered in a document. The encountered in a document. The exceptions to this rule include the exceptions to this rule include the followingfollowing Scripting being disabled in the user Scripting being disabled in the user

agent.agent. The defer attribute being set in the The defer attribute being set in the

<script> tag.<script> tag. All code being contained within All code being contained within

functions that are not explicitly functions that are not explicitly called during the document’s called during the document’s rendering.rendering.

We can force a script to run We can force a script to run immediately after the document is immediately after the document is loaded by using the onload event in the loaded by using the onload event in the <body> tag:<body> tag:

<body onload=“ScriptFunctionName”><body onload=“ScriptFunctionName”>

<html> <head><html> <head><script type=“text/javascript”><script type=“text/javascript”> function runmelater() {function runmelater() { // script code// script code }}</script></script></head></head><body><body><p><p> <script type=“text/javascript”><script type=“text/javascript”> // script code (not enclosed in // script code (not enclosed in

function(s))function(s)) </script></script></p></p></body></body><html><html>

Page 9: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 9

Basic JavaScript Syntax

JavaScript follows fairly basic syntax that can be outlined with a JavaScript follows fairly basic syntax that can be outlined with a few simple rules:few simple rules:

All code should appear within appropriate constructs, namely All code should appear within appropriate constructs, namely between <script> tags or within event attributes.between <script> tags or within event attributes.With few exceptions, code lines should end with a semicolon With few exceptions, code lines should end with a semicolon (;). Notable exceptions to this rule are lines that end in a block (;). Notable exceptions to this rule are lines that end in a block delimiter ({ or }).delimiter ({ or }).Blocks of code (usually under control structures such as Blocks of code (usually under control structures such as functions, if statements, and so on) are enclosed in braces ({ and functions, if statements, and so on) are enclosed in braces ({ and }).}).Although it is not absolutely necessary, explicit declaration of Although it is not absolutely necessary, explicit declaration of all variables is a good idea.all variables is a good idea.The use of functions to delimit code fragments is The use of functions to delimit code fragments is recommended.recommended.Comments can be inserted in JavaScript code by prefixing the Comments can be inserted in JavaScript code by prefixing the comment with a double-slash (//) or surrounded the comment comment with a double-slash (//) or surrounded the comment with /* and */ pairswith /* and */ pairs

Page 10: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 10

Data Types and Variables

JavaScript, like most other programming languages, supports a wide range of JavaScript, like most other programming languages, supports a wide range of data types. However, JavaScript employs little data type checking. JavaScript data types. However, JavaScript employs little data type checking. JavaScript supports the following data types:supports the following data types: BooleansBooleans IntegersIntegers Floating –point numbersFloating –point numbers StringsStrings ArraysArrays

Examples: Examples:

a = new Array();a = new Array();

months = new (“JAN”, “FEB”, “MAR, “APR”, “MAY, “JUN”, “JUL”, …, months = new (“JAN”, “FEB”, “MAR, “APR”, “MAY, “JUN”, “JUL”, …, “DEC”);“DEC”);

s = new String ();s = new String ();

n = new Number ();n = new Number ();

Page 11: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 11

Variables

JavaScript variables are JavaScript variables are case sensitive and can case sensitive and can contain a mix of letters and contain a mix of letters and numbers.numbers.

JavaScript uses the JavaScript uses the varvar statement to explicitly statement to explicitly declare variables,declare variables,

Examples: Examples: var x;var x;

var x = 20;var x = 20; var x = 20, Lastname = var x = 20, Lastname =

‘Khalil’;‘Khalil’; JavaScript variables have JavaScript variables have

global scope unless they are global scope unless they are declared within a function. declared within a function.

For example, in the For example, in the following code the variable following code the variable x is global while variable y x is global while variable y is local to the function:is local to the function:

<script <script type=“text/javascript”>type=“text/javascript”>

var x = 100;var x = 100; function spacefill(text, function spacefill(text,

amount) {amount) { var y = 0;var y = 0; … … }}</script></script>

Page 12: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 12

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>

Page 13: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 13

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>

Page 14: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 14

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>

Page 15: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 15

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>

Page 16: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 16

JavaScript Arithmetic Operators

Operator Use

++ AdditionAddition

-- SubtractionSubtraction

** MultiplicationMultiplication

// DivisionDivision

%% ModulusModulus

++++ IncrementIncrement

---- DecrementDecrement

Page 17: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 17

JavaScript Assignment Operators

Operator Use

== AssignmentAssignment

+=+= Increment assignmentIncrement assignment

-=-= Decrement assignmentDecrement assignment

*=*= Multiplication assignmentMultiplication assignment

/=/= Division assignmentDivision assignment

%=%= Modulus assignmentModulus assignment

Page 18: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 18

Assignment Operators

Assignment Operator

Initial variable Value

Sample expression

Explanation ASSIGNS

+=+= 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

Page 19: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 19

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>

Page 20: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 20

Example 5 – Adding Integers

Page 21: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 21

JavaScript Comparison Operators

Operator Use

==== Is equal toIs equal to

====== Exactly equal to – in value and typeExactly equal to – in value and type

!=!= Is not equal toIs not equal to

>> Is greater thanIs greater than

<< Is less thanIs less than

>=>= Is greater than or equal toIs greater than or equal to

<=<= Is less than or equal toIs less than or equal to

Page 22: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 22

JavaScript Logical Operators

Operator Use

&&&& AndAnd

││││ OrOr

!! NotNot

Page 23: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 23

Demonstrating the Logical Operators

<HTML><HEAD><TITLE>Demonstrating the logical operators</TITLE><HTML><HEAD><TITLE>Demonstrating the logical operators</TITLE><SCRIPT LANGUAGE="JavaScript"><SCRIPT LANGUAGE="JavaScript">

document.writeln( "<TABLE BORDER='10' WIDTH='100%'>" );document.writeln( "<TABLE BORDER='10' WIDTH='100%'>" );

document.writeln(document.writeln( "<TR><TD WIDTH= '25%'>Logical AND (&&)</TD>" +"<TR><TD WIDTH= '25%'>Logical AND (&&)</TD>" +

"<TD>false && false: " + ( false && false ) +"<TD>false && false: " + ( false && false ) + "<BR>false && true: " + ( false && true ) +"<BR>false && true: " + ( false && true ) + "<BR>true && false: " + ( true && false ) +"<BR>true && false: " + ( true && false ) + "<BR>true && true: " + ( true && true ) + "</TD>" );"<BR>true && true: " + ( true && true ) + "</TD>" );

document.writeln(document.writeln( "<TR><TD WIDTH= '25%'>Logical OR (||)</TD>" +"<TR><TD WIDTH= '25%'>Logical OR (||)</TD>" + "<TD>false || false: " + ( false || false ) +"<TD>false || false: " + ( false || false ) +

"<BR>false || true: " + ( false || true ) +"<BR>false || true: " + ( false || true ) + "<BR>true || false: " + ( true || false ) +"<BR>true || false: " + ( true || false ) + "<BR>true || true: " + ( true || true ) + "</TD>" );"<BR>true || true: " + ( true || true ) + "</TD>" );

document.writeln(document.writeln( "<TR><TD WIDTH= '25%'>Logical NOT (!)</TD>" +"<TR><TD WIDTH= '25%'>Logical NOT (!)</TD>" + "<TD>!false: " + ( !false ) +"<TD>!false: " + ( !false ) +

"<BR>!true: " + ( !true ) + "</TD>" );"<BR>!true: " + ( !true ) + "</TD>" );

doccument.writeln( "</TABLE>" );doccument.writeln( "</TABLE>" );</SCRIPT></SCRIPT></HEAD><BODY></BODY></HEAD><BODY></BODY></HTML></HTML>

Page 24: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 24

Page 25: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 25

JavaScript String Operators

Operator Use

++ ConcatenationConcatenation

Page 26: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 26

JavaScript String Tokens

Token Character

\\ BackslashBackslash

\’ Single quoteSingle quote

\” Double quoteDouble quote

\b BackspaceBackspace

\f Form FeedForm Feed

\n Line FeedLine Feed

\r Carriage ReturnCarriage Return

\t Horizontal TabHorizontal Tab

\v Vertical TabVertical Tab

Page 27: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 27

Control Structures

if structure

if ( <condition> ) {

// statement(s) to execute if condition is true

} [ else {

// statement(s) to execute if condition is false

}]

Page 28: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 28

Control Structures (Cont’d)

if structureif ( 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” );

}

Page 29: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 29

Control Structures (Cont’d)

Nested-if structureif ( 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” );

Page 30: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 30

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”;}

Page 31: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 31

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>

Page 32: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 32

Page 33: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 33

Page 34: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 34

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;

}----------------------------------

Page 35: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 35

Repetition - Counter-controlled while loop

<<HTML>HTML><HEAD><HEAD><TITLE>Counter-controlled loops</TITLE><TITLE>Counter-controlled loops</TITLE><SCRIPT LANGUAGE="JavaScript"> <SCRIPT LANGUAGE="JavaScript">

var counter = 1;var counter = 1; // initialize the counter// initialize the counterwhile ( counter <= 7 )while ( counter <= 7 ) // loop condition// loop condition{{ document.writeln( "<p><FONT SIZE = '" + counter + "'>HTML document.writeln( "<p><FONT SIZE = '" + counter + "'>HTML

font size " +font size " + counter + "</FONT></p>" );counter + "</FONT></p>" );

++counter;++counter; // increment// increment }}</SCRIPT></SCRIPT></HEAD><BODY></BODY></HEAD><BODY></BODY></HTML></HTML>

Page 36: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 36

Page 37: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 37

Counter-controlled loop – An Example

<HTML><HEAD><TITLE>Class Average Program</TITLE><HTML><HEAD><TITLE>Class Average Program</TITLE><SCRIPT LANGUAGE="JavaScript"> <SCRIPT LANGUAGE="JavaScript">

var total,var total, // sum of grades// sum of grades gradeCounter,gradeCounter, // number of grades entered// number of grades entered gradeValue,gradeValue, // grade value// grade value average,average, // average of all grades// average of all grades grade;grade; // grade typed by uesr// grade typed by uesr// initialization phase// initialization phasetotal = 0;total = 0; // clear total// clear totalgradeCounter = 1;gradeCounter = 1; // initialize the counter// initialize the counter// processing phase// processing phasewhile ( gradeCounter <= 10 ) {while ( gradeCounter <= 10 ) { grade = window.prompt ( "Enter integer grade:", "0" );grade = window.prompt ( "Enter integer grade:", "0" ); gradeValue = parseInt( grade );gradeValue = parseInt( grade ); total = total + gradeValue;total = total + gradeValue; gradeCounter = gradeCounter + 1;gradeCounter = gradeCounter + 1;}}average = total / 10;average = total / 10;document.writeln( "<H1>Class average is " + average + "</H1>" );document.writeln( "<H1>Class average is " + average + "</H1>" );

</SCRIPT></SCRIPT></HEAD><BODY>Refresh to run the script again</BODY></HEAD><BODY>Refresh to run the script again</BODY></HTML></HTML>

Page 38: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 38

Page 39: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 39

Repetition Structures – do while Loop

do while

do { // statement(s) to execute }While ( <condition> );

Examples

X = 0;do { x++; // increment x } while (x < 20);

Page 40: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 40

The do/while loop

<HTML><HTML><HEAD><HEAD><TITLE>Using the do/while loop</TITLE><TITLE>Using the do/while loop</TITLE><SCRIPT LANGUAGE="JavaScript"> <SCRIPT LANGUAGE="JavaScript">

var counter = 1;var counter = 1;do {do { document.writeln( "<H" + counter + ">This is an H" + counter + " level head" + "</H" +document.writeln( "<H" + counter + ">This is an H" + counter + " level head" + "</H" +

counter + ">" );counter + ">" ); ++ counter;++ counter;} while ( counter <= 6 );} while ( counter <= 6 );

</SCRIPT></SCRIPT></HEAD><BODY></BODY></HEAD><BODY></BODY></HTML></HTML>

Page 41: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 41

for loop

General Format:General Format:

for ( initialization; loopContinuationTest; increment ) ( initialization; loopContinuationTest; increment )

statementstatement------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------<HTML><HTML><HEAD><HEAD><TITLE>Counter-controlled loops</TITLE><TITLE>Counter-controlled loops</TITLE><SCRIPT LANGUAGE="JavaScript"> <SCRIPT LANGUAGE="JavaScript">

// Initialization, loop condition and incrementing// Initialization, loop condition and incrementing// are all included in the for structure header.// are all included in the for structure header. for ( var counter = 1; counter <= 7; ++counter )for ( var counter = 1; counter <= 7; ++counter )

document.writeln( "<p><FONT SIZE = '" + counter + "'>HTML font size " +document.writeln( "<p><FONT SIZE = '" + counter + "'>HTML font size " + counter + "</FONT></p>" );counter + "</FONT></p>" );

</SCRIPT></SCRIPT></HEAD><BODY></BODY></HEAD><BODY></BODY></HTML></HTML>

Page 42: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 42

Page 43: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 43

Sentinel-controlled loop

<HTML><HEAD><TITLE>Class Average Program</TITLE><HTML><HEAD><TITLE>Class Average Program</TITLE><SCRIPT LANGUAGE="JavaScript"> <SCRIPT LANGUAGE="JavaScript">

var total,var total, // sum of grades// sum of grades gradeCounter,gradeCounter, // number of grades entered// number of grades entered gradeValue,gradeValue, // grade value// grade value average,average, // average of all grades// average of all grades grade;grade; // grade typed by uesr// grade typed by uesr// initialization phase// initialization phasetotal = 0;total = 0; // clear total// clear totalgradeCounter = 0;gradeCounter = 0; // initialize the counter// initialize the counter// processing phase// processing phase// prompt for input and read grade from user// prompt for input and read grade from usergrade = window.prompt ( "Enter integer grade, -1 to Quit:", "0" );grade = window.prompt ( "Enter integer grade, -1 to Quit:", "0" );gradeValue = parseInt( grade );gradeValue = parseInt( grade );while ( gradeValue != -1 ) {while ( gradeValue != -1 ) { total = total + gradeValue;total = total + gradeValue; gradeCounter = gradeCounter + 1;gradeCounter = gradeCounter + 1; grade = window.prompt ( "Enter integer grade, -1 to Quit:", "0" );grade = window.prompt ( "Enter integer grade, -1 to Quit:", "0" ); gradeValue = parseInt( grade );gradeValue = parseInt( grade );}}if ( gradeCounter != 0 ) {if ( gradeCounter != 0 ) { average = total / gradeCounter;average = total / gradeCounter; document.writeln( "<H1>Class average is " + average + "</H1>" );document.writeln( "<H1>Class average is " + average + "</H1>" );}}elseelse document.writeln( "<p>No grades were entered!!" );document.writeln( "<p>No grades were entered!!" );

</SCRIPT></SCRIPT></HEAD><BODY>Refresh to run the script again</BODY></HEAD><BODY>Refresh to run the script again</BODY></HTML></HTML>

Page 44: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 44

Page 45: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 45

Calculating Compound Interest with for loop

<HTML><HEAD><TITLE>Calculating Compound Interest</TITLE><HTML><HEAD><TITLE>Calculating Compound Interest</TITLE><SCRIPT LANGUAGE="JavaScript"><SCRIPT LANGUAGE="JavaScript">

var amount, principal = 1000, rate = 0.1;var amount, principal = 1000, rate = 0.1;

document.writeln( "<TABLE BORDER='100' WIDTH='100%'>" );document.writeln( "<TABLE BORDER='100' WIDTH='100%'>" );document.writeln( "<TR><TD WIDTH= '100'><B>Year</B></TD>" );document.writeln( "<TR><TD WIDTH= '100'><B>Year</B></TD>" );document.writeln( "<TD><B>Amount on deposit</B></TD></TR>" );document.writeln( "<TD><B>Amount on deposit</B></TD></TR>" );

for ( var year = 1; year <= 10; ++year ) {for ( var year = 1; year <= 10; ++year ) { amount = principal * Math.pow(1.0 + rate, year);amount = principal * Math.pow(1.0 + rate, year); document.writeln( "<TR><TD>" + year + "</TD><TD>" + document.writeln( "<TR><TD>" + year + "</TD><TD>" +

Math.round(amount * 100) / 100 + "<TD></TR>" );Math.round(amount * 100) / 100 + "<TD></TR>" );}}

doccument.writeln( "</TABLE>" );doccument.writeln( "</TABLE>" );</SCRIPT></SCRIPT></HEAD><BODY></BODY></HEAD><BODY></BODY></HTML></HTML>

Page 46: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 46

Page 47: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 47

Page 48: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 48

Break and Continue

var x = 1;var x = 1;

while (x <= 20) {while (x <= 20) {

if (x == 7) continue; // skip the number 7if (x == 7) continue; // skip the number 7

// statement(s) to execute if x does not equal 7// statement(s) to execute if x does not equal 7

}}

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

var y = 1;var y = 1;

while (y <= 20) {while (y <= 20) {

if (x == 100) break; // if x = 100, leave the loopif (x == 100) break; // if x = 100, leave the loop

// statement(s) to execute // statement(s) to execute

}}

// execution continues here when y > 20 or x = 100// execution continues here when y > 20 or x = 100

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Page 49: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 49

Labels

var x = 100;var x = 100;code_loop:code_loop:while (x <= 1000) {while (x <= 1000) { // statement(s)// statement(s) }}------------------------------------------------------------------------------------------------------------------------------------------------------------------------------var x = 0, y = 0;var x = 0, y = 0;top_loop:top_loop:while (x <= 100) {while (x <= 100) { while (y <= 50) {while (y <= 50) { …………… …………… if (z == 100) break top_loop;if (z == 100) break top_loop; }} }}// execution resumes here after loops are complete or if z = 100 during the loops execution// execution resumes here after loops are complete or if z = 100 during the loops execution-------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------

code_block: {code_block: { // block of code here// block of code here }}

Page 50: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 50

Functions Experience has shown that the best way to develop and maintain a large program is to 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 construct it from small, simple pieces or modules. This technique is called divide and divide and conquer.conquer.

Modules in JavaScript are called functions. JavaScript programs are written by combining Modules in JavaScript are called functions. JavaScript programs are written by combining new functions that the programmer writes with “prepackaged” functions and objects new functions that the programmer writes with “prepackaged” functions and objects available in JavaScript.available in JavaScript.

The “prepackaged” functions that belong to JavaScript objects are often called 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 term method implies that the function belongs to a particular object.

The programmer can write programmer-defined functions to define specific tasks that may 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 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.only once, and these statements are hidden from other functions.

A A function is invoked by a function call. The function call specifies the function name and 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.provides information (as arguments) that the called function needs to do its task.

Functions allow the programmer to modularize a program.Functions allow the programmer to modularize a program. All variables declared in function definitions are local variables – they are known only in All variables declared in function definitions are local variables – they are known only in

the function in which they are defined.the function in which they are defined. Most functions have parameters that provide the means for communicating information 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 between functions via function calls. A function’s parameters are also considered to be local variables.local variables.

The divide-conquer approach to program development makes program development more The divide-conquer approach to program development makes program development more manageable.manageable.

Page 51: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 51

Functions The The () represent the function call operator represent the function call operator The The return statement passes the result of a function call back to statement passes the result of a function call back to

the calling function.the calling function. The format of a function definition isThe format of a function definition is

Function function-namefunction-name( ( parameter-listparameter-list ) )

{{

declarations and statementsdeclarations and statements

}}

Page 52: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 52

Built-in FunctionsFunction Use Returns

escapeescape Creates portable data – typically used to encode Creates portable data – typically used to encode URLs and other information that may include URLs and other information that may include extended characters (non-alphanumeric). extended characters (non-alphanumeric). Extended characters are replaced by their ASCII Extended characters are replaced by their ASCII number equivalent in hexadecimal %xx form. For number equivalent in hexadecimal %xx form. For example, a space (ASCII 20) becomes %20.example, a space (ASCII 20) becomes %20.

Encoded version of supplied argumentEncoded version of supplied argument

evaleval Parse the supplied string for JavaScript code and Parse the supplied string for JavaScript code and executes the code if foundexecutes the code if found

The value of the last valid statement or The value of the last valid statement or expression encountered in the supplied expression encountered in the supplied argument.argument.

isFiniteisFinite Tests an expression or variable to see if it is a Tests an expression or variable to see if it is a valid number.valid number.

True if the supplied argument is a Valid True if the supplied argument is a Valid number, false otherwise.number, false otherwise.

isNaNisNaN Tests an expression or variable to see if it is not a Tests an expression or variable to see if it is not a ((valid) number.((valid) number.

Returns true if the argument is not a number Returns true if the argument is not a number and false otherwise.and false otherwise.

numbernumber Converts an object (typically string data) to a Converts an object (typically string data) to a number.number.

Returns the supplied argument converted to a Returns the supplied argument converted to a number or the value NaN if the argument number or the value NaN if the argument cannot be converted to a valid number.cannot be converted to a valid number.

parseFloatparseFloat Parses the given argument for a valid floating-Parses the given argument for a valid floating-point number.point number.

A floating-point representation of the supplied A floating-point representation of the supplied argument.argument.

parseIntparseInt Parses the given argument for a valid integer Parses the given argument for a valid integer number.number.

An integer representation of the supplied An integer representation of the supplied argument.argument.

stringstring Converts the supplied argument to a string Converts the supplied argument to a string representation.representation.

A string representation of the supplied A string representation of the supplied argument.argument.

UnescapeUnescape Converts portable data back into its original form.Converts portable data back into its original form. Decoded version of the supplied argumemt.Decoded version of the supplied argumemt.

Page 53: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 53

User-Defined Functions JavaScript supports user-defined functions which allow users to better JavaScript supports user-defined functions which allow users to better

organize their code into discrete, reusable chunks. User-defined functions organize their code into discrete, reusable chunks. User-defined functions have the following syntax:have the following syntax:

function <function_name> ( <list_of_arguments> ) {… code of function …

return <value_to_return>;} For example:For example:function spacefill(text) {

while (text.length < 25) { text = text + “ “; } return text;}----------------------------------------------------------------------------------- Elsewhere in your code, you can use this function:Elsewhere in your code, you can use this function:

address = spacefill(address);

Page 54: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 54

Example – User-defined Functions

<HTML><HEAD><TITLE>A Programmer-Defined Square Function</TITLE><HTML><HEAD><TITLE>A Programmer-Defined Square Function</TITLE>

<SCRIPT LANGUAGE="JavaScript"> <SCRIPT LANGUAGE="JavaScript">

document.writeln( "<H1>Square the numbers from 1 to 10</H1>" );document.writeln( "<H1>Square the numbers from 1 to 10</H1>" );

// square the numbers from 1 to 10// square the numbers from 1 to 10for ( var x = 1; x <= 10; ++x )for ( var x = 1; x <= 10; ++x )

document.writeln( "The square of " + x + " is " + square( x ) + "<BR>" );document.writeln( "The square of " + x + " is " + square( x ) + "<BR>" );

// square function definition// square function definitionfunction square( y )function square( y ){{

return y * y;return y * y;}}

</SCRIPT></SCRIPT></HEAD><BODY></BODY></HEAD><BODY></BODY></HTML></HTML>

Page 55: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 55

Page 56: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 56

<HTML><HEAD><TITLE>A Programmer-Defined maximum Function</TITLE><HTML><HEAD><TITLE>A Programmer-Defined maximum Function</TITLE><SCRIPT LANGUAGE="JavaScript"> <SCRIPT LANGUAGE="JavaScript">

var input1 = window.prompt( "Enter first number", "0" );var input1 = window.prompt( "Enter first number", "0" );var input2 = window.prompt( "Enter second number", "0" );var input2 = window.prompt( "Enter second number", "0" );var input3 = window.prompt( "Enter third number", "0" );var input3 = window.prompt( "Enter third number", "0" );

var value1 = parseInt( input1 );var value1 = parseInt( input1 );var value2 = parseInt( input2 );var value2 = parseInt( input2 );var value3 = parseInt( input3 );var value3 = parseInt( input3 );

var maxValue = maximum( value1, value2, value3 );var maxValue = maximum( value1, value2, value3 );document.writeln( "First number: " + value1 + "<BR>Second number: " + value2 +document.writeln( "First number: " + value1 + "<BR>Second number: " + value2 +

"<BR>Third number: " + value3 + "<BR> Maximum is: " +"<BR>Third number: " + value3 + "<BR> Maximum is: " +maxValue );maxValue );

// maximum function definition// maximum function definitionfunction maximum( x, y, z )function maximum( x, y, z ){{

return Math.max( x, Math.max( y, z ) );return Math.max( x, Math.max( y, z ) );}}

</SCRIPT></SCRIPT></HEAD><BODY></BODY></HEAD><BODY></BODY></HTML></HTML>

Page 57: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 57

Objects Objects are a natural way of thinking about the world.are a natural way of thinking about the world. Objects encapsulate data (attributes) and methods (behavior).Objects encapsulate data (attributes) and methods (behavior). Objects have the property of information hiding.Objects have the property of information hiding. Programs communicate with objects by using well-defined interfaces. Programs communicate with objects by using well-defined interfaces. World Wide Web browsers have a set of objects that encapsulate the elements 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 of an HTML document and expose to a JavaScript programmer attributes and behaviors that enable a JavaScript program to interact with (or script) the behaviors that enable a JavaScript program to interact with (or script) the elements (i.e., objects) in an HTML document.elements (i.e., objects) in an HTML document.

Math object methods allow programmers to perform many common object methods allow programmers to perform many common mathematical calculations.mathematical calculations.

An object’s methods are called by writing the name of the object followed by a 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 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.is the argument (or a comma-separated list of arguments) to the method.

String object provides several methods enabling processing String objects. object provides several methods enabling processing String objects.

Page 58: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 58

Built-in Objects JavaScript is an object-driven language. JavaScript is an object-driven language.

“The Document Object Model” – the user “The Document Object Model” – the user agent – supplies a host of objects that your agent – supplies a host of objects that your scripts can reference.scripts can reference.

JavaScript has several built-in objects. For JavaScript has several built-in objects. For example, two specific objects exist for example, two specific objects exist for manipulating data: one for performing math manipulating data: one for performing math

operations (operations (Math) on numeric data and ) on numeric data and another for performing operations on string another for performing operations on string

values (values (String).). These objects have various methods for These objects have various methods for

acting upon data: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:JavaScript also supports the with statement:with (Math) {

y = random(200); x = round (sqrt(y)); }

Another useful object is the Another useful object is the Date object which has several methods object which has several methods that can be used to manipulate that can be used to manipulate dates and times in various formats: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>

Page 59: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 59

Methods The The Math object’s object’s max method determines the larger of its two method determines the larger of its two

statement values.statement values. The The Math object’s object’s random method generates a real value from method generates a real value from

0.0 up to (but not including) 1.0.0.0 up to (but not including) 1.0. Math object’s object’s floor rounds its real number argument to the closest rounds its real number argument to the closest

integer not greater than its argument’s value.integer not greater than its argument’s value. The values produced directly by random are always in the range: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 We can generalize picking a random number from a range of

values by writing:values by writing:value = Math.floor( a + Math.random() * b) ;

Where Where a is the is the shifting valueshifting value (the first number in the desired (the first number in the desired range of consecutive integers) and range of consecutive integers) and b is the is the scaling factorscaling factor (the (the width of the desired range of consecutive integers).width of the desired range of consecutive integers).

Page 60: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 60

Math Object’s Methods

Method Description Method Description

abs( x )abs( x ) Absolute value of xAbsolute value of x round( x )round( x ) Rounds x to the closest Rounds x to the closest integerinteger

ceil( x )ceil( x ) Rounds x to the smallest integer Rounds x to the smallest integer not less than xnot less than x

sin( x )sin( x ) Trigonometric sine of x (x Trigonometric sine of x (x in radians)in radians)

cos( x )cos( x ) Trigonometric cosine of x (x in Trigonometric cosine of x (x in radians)radians)

sqrt( x )sqrt( x ) Square root of xSquare root of x

exp( x )exp( x ) Exponential method eExponential method exx tan( x )tan( x ) Trigonometric tangent of x Trigonometric tangent of x (x in radians)(x in radians)

floor( x )floor( x ) Rounds x to the largest integer not Rounds x to the largest integer not greater than xgreater than x

log( x )log( x ) Natural logarithm of x (base Natural logarithm of x (base ee))

max( x, y )max( x, y ) Larger value of x and yLarger value of x and y

min( x, y )min( x, y ) Smaller value of x and ySmaller value of x and y

pow( x, y )pow( x, y ) X raised to power y (xX raised to power y (xyy))

Page 61: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 61

Random Number Generation<HTML><HEAD><TITLE>Shifted and Scaled Random Integers</TITLE><HTML><HEAD><TITLE>Shifted and Scaled Random Integers</TITLE><SCRIPT LANGUAGE="JavaScript"> <SCRIPT LANGUAGE="JavaScript">

var value;var value;document.writeln( "<H1>Random Numbers</H1>" + document.writeln( "<H1>Random Numbers</H1>" +

"<TABLE BORDER = '5' WIDTH = '50%'><TR>" );"<TABLE BORDER = '5' WIDTH = '50%'><TR>" );

for ( var i = 1; i <= 20; i++ ) {for ( var i = 1; i <= 20; i++ ) {value = Math.floor( 1 + Math.random() * 6 );value = Math.floor( 1 + Math.random() * 6 );document.writeln( "<TD>" + value + "</TD>" );document.writeln( "<TD>" + value + "</TD>" );

if ( i % 5 == 0 && i != 20 )if ( i % 5 == 0 && i != 20 )document.writeln( "</TR><TR>" );document.writeln( "</TR><TR>" );

}}document.writeln( "</TR></TABLE>" );document.writeln( "</TR></TABLE>" );

</SCRIPT></SCRIPT></HEAD><BODY></BODY></HTML></HEAD><BODY></BODY></HTML>

Page 62: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 62

Page 63: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 63

User-Created Objects The new declaration statement can be used to create new objects based on existing, built-The new declaration statement can be used to create new objects based on existing, built-

in objects, for example:in objects, for example:

employees = new Array(“Khalil”, “Sameh”, “Sherif”, “Amr”, “Khaled”);

JavaScript also includes built-in constructors for native objects: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: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: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”;

Page 64: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 64

Arrays Arrays are data structures consisting of related data items. 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 An array is a group of memory locations that all have the same name and are normally of

the same type. the same type. To refer to a particular location or element in the array, specify the name of the array and To refer to a particular location or element in the array, specify the name of the array and

the position number (the position number (index) of the particular element in the array.) of the particular element in the array. The index (or The index (or subscript) must be an integer or an integer expression and the first ) must be an integer or an integer expression and the first

element in every array is of index element in every array is of index 0.. The length (size) of an array is the number of its elements and is determined by The length (size) of an array is the number of its elements and is determined by

arrayName.arrayName.length.. An array in JavaScript is an An array in JavaScript is an Array object. Operator object. Operator new is used to dynamically allocate is used to dynamically allocate

the number of elements required by an array. Operator the number of elements required by an array. Operator new creates an object as the creates an object as the program executes, by obtaining enough memory to store an object of the type specified program executes, by obtaining enough memory to store an object of the type specified to the right of to the right of new..

The process of creating new objects is also known as creating an instance or instantiating The process of creating new objects is also known as creating an instance or instantiating an object.an object.

An array can be initialized with a comma-separated initializerl ist enclosed in square An array can be initialized with a comma-separated initializerl ist enclosed in square brackets [ ]. brackets [ ].

JavaScript’s for/in control structure enables a script to perform a task for each element in JavaScript’s for/in control structure enables a script to perform a task for each element in an array:an array:for ( var element in arrayName ) ( var element in arrayName )

statementstatement

Page 65: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 65

Arrays – An Example I<HTML><HEAD><TITLE>Initializing an Array</TITLE><HTML><HEAD><TITLE>Initializing an Array</TITLE><SCRIPT LANGUAGE="JavaScript"> <SCRIPT LANGUAGE="JavaScript">

// this function is called when the <BODY> element's // this function is called when the <BODY> element's // ONLOAD event occurs.// ONLOAD event occurs.function initializeArrays() {function initializeArrays() {

var n1 = new Array( 5 );var n1 = new Array( 5 ); // allocate 5-element Array// allocate 5-element Arrayvar n2 = new Array();var n2 = new Array(); // allocate empty Array // allocate empty Array // assign values to each element of Array n1// assign values to each element of Array n1for ( var i = 0; i < n1.length; ++i )for ( var i = 0; i < n1.length; ++i )

n1[i] = i * i;n1[i] = i * i;// create and initialize 6 elements in Array n2// create and initialize 6 elements in Array n2for ( i = 0; i < 6; ++i )for ( i = 0; i < 6; ++i )

n2[i] = 2 * i;n2[i] = 2 * i;outputArray( "Array n1 contains", n1 );outputArray( "Array n1 contains", n1 );outputArray( "Array n2 contains", n2 );outputArray( "Array n2 contains", n2 );

}}// output "header" followed by a two-column table// output "header" followed by a two-column table// containing subscripts and elements of "theArray"// containing subscripts and elements of "theArray"function outputArray( header, theArray )function outputArray( header, theArray ){{

document.writeln( "<H2>" + header + "</H2>" );document.writeln( "<H2>" + header + "</H2>" );document.writeln( "<TABLE BORDER='10' WIDTH='100%'>" );document.writeln( "<TABLE BORDER='10' WIDTH='100%'>" );document.writeln( "<TR><TD WIDTH='100'><B>Subscript</B>“ + "<TD><B>Value</B></TR>" );document.writeln( "<TR><TD WIDTH='100'><B>Subscript</B>“ + "<TD><B>Value</B></TR>" );

for ( var i = 0; i < theArray.length; i++ )for ( var i = 0; i < theArray.length; i++ )document.writeln( "<TR><TD>" + i + "<TD>" + theArray[i] + "</TR>" );document.writeln( "<TR><TD>" + i + "<TD>" + theArray[i] + "</TR>" );document.writeln( "</TABLE>" );document.writeln( "</TABLE>" );

}}</SCRIPT></SCRIPT></HEAD></HEAD><BODY ONLOAD = "initializeArrays()"><BODY ONLOAD = "initializeArrays()"></BODY></BODY></HTML></HTML>

Page 66: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 66

Page 67: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 67

Arrays – An Example II

<HTML><HEAD><TITLE>Student Poll Program</TITLE><HTML><HEAD><TITLE>Student Poll Program</TITLE><SCRIPT LANGUAGE="JavaScript"> <SCRIPT LANGUAGE="JavaScript">

function start()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,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 ];5, 6, 7, 5, 6, 4, 8, 6, 8, 10 ];

var frequency = [ , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ];var frequency = [ , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ];for ( var answer in responses )for ( var answer in responses )

++frequency[ responses[ answer ] ];++frequency[ responses[ answer ] ];

document.writeln( "<TABLE BORDER='10' WIDTH='100%'>" );document.writeln( "<TABLE BORDER='10' WIDTH='100%'>" );document.writeln( "<TR><TD WIDTH='100'><B>Rating</B>"document.writeln( "<TR><TD WIDTH='100'><B>Rating</B>"

+ "<TD><B>Frequency</B></TR>" );+ "<TD><B>Frequency</B></TR>" );

for ( var rating = 1; rating < frequency.length; ++rating )for ( var rating = 1; rating < frequency.length; ++rating )document.writeln( "<TR><TD>" + rating + "<TD>" + document.writeln( "<TR><TD>" + rating + "<TD>" +

frequency[rating] + "<TR>" );frequency[rating] + "<TR>" );

document.writeln( "</TABLE>" );document.writeln( "</TABLE>" );}}

</SCRIPT></SCRIPT></HEAD></HEAD><BODY ONLOAD = "start()"><BODY ONLOAD = "start()"></BODY></HTML></BODY></HTML>

Page 68: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 68

Page 69: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 69

Event Handling One of the more powerful anf often used techniques concerning JavaScript is One of the more powerful anf often used techniques concerning JavaScript is

events. Using event attributes in XHTML tags, such as onmouseover and events. Using event attributes in XHTML tags, such as onmouseover and onclick, you can create interactive documents that respond to user’s actions.onclick, you can create interactive documents that respond to user’s actions.

EventEvent TriggerTrigger

onAbortonAbort Abort selected in browser (stop loading of image or document), usually by Abort selected in browser (stop loading of image or document), usually by clicking the Stop buttonclicking the Stop button

onBluronBlur When the object loses focusWhen the object loses focus

onChangeonChange When an object is changed (generally a form element)When an object is changed (generally a form element)

onClickonClick When the object is clickedWhen the object is clicked

onDblClickonDblClick When the object is double-clickedWhen the object is double-clicked

onDragDroponDragDrop When a object is dropped into the user agent windowWhen a object is dropped into the user agent window

onErroronError When a JavaScript error occursWhen a JavaScript error occurs

onFocusonFocus When an object receives focusWhen an object receives focus

onKeyDownonKeyDown When the user presses a keyWhen the user presses a key

onKeyPressonKeyPress When the user presses and/or holds down a keyWhen the user presses and/or holds down a key

onKeyUponKeyUp When the user releases a keyWhen the user releases a key

OnloadOnload When the object is loaded into the user agent window (typically used with 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 the <body> element to run a script when the document has completed loading)loading)

Page 70: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 70

Event Handling (Cont’d)

EventEvent TriggerTrigger

onMouseDownonMouseDown When the mouse butoon is depressedWhen the mouse butoon is depressed

onMouseMoveonMouseMove When the mouse is movedWhen the mouse is moved

onMouseOutonMouseOut When the mouse pointer moves outside the boundary of an objectWhen the mouse pointer moves outside the boundary of an object

onMouseOveronMouseOver When the mouse pointer moves within the boundary of an objectWhen the mouse pointer moves within the boundary of an object

onMouseUponMouseUp When the mouse button is releasedWhen the mouse button is released

onMoveonMove When an object (generally a window or frame) is movedWhen an object (generally a window or frame) is moved

onResetonReset When the user selects a reset buttonWhen the user selects a reset button

onResizeonResize When an object (generally a window or frame) is resizedWhen an object (generally a window or frame) is resized

onSelectonSelect When the user selects text within the object (generally a form element)When the user selects text within the object (generally a form element)

onSubmitonSubmit When the user selects a submit buttonWhen the user selects a submit button

OnUnloadOnUnload When the object is unloaded from the user agent window (typically used 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 with the <body> element to run a script when the user navigates away from a document – a favorite tool of pop-up window coders)from a document – a favorite tool of pop-up window coders)

Page 71: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 71

Key Points The The JavaScript language facilitates a disciplined approach to designing computer language facilitates a disciplined approach to designing computer

programs that enhance Web pages.programs that enhance Web pages. Often JavaScripts appear in the Often JavaScripts appear in the <HEAD> section of the HTML document. section of the HTML document. The browser interprets the contents of the The browser interprets the contents of the <HEAD> section first. section first. The The <SCRIPT> tag indicates to the browser that the text that follows is part of a tag indicates to the browser that the text that follows is part of a

script. Attribute script. Attribute LANGUAGE specifies the scripting language used in the script – specifies the scripting language used in the script – such as such as JavaScript.

Every statement should end with a semicolon.Every statement should end with a semicolon. JavaScript is case sensitive.JavaScript is case sensitive. A string of characters can be contained between the double quotation (“) marks or A string of characters can be contained between the double quotation (“) marks or

single quotation (‘) marks.single quotation (‘) marks. A string is sometimes called a character string, a message or string literal.A string is sometimes called a character string, a message or string literal. The browser’s The browser’s document object represents the HTML document currently being object represents the HTML document currently being

displayed in the browser. The document object allows a script programmers to specify displayed in the browser. The document object allows a script programmers to specify HTML text to be displayed in the HTML document.HTML text to be displayed in the HTML document.

The browser contains a complete set of objects that allow script programmers every The browser contains a complete set of objects that allow script programmers every element of an HTML document.element of an HTML document.

An object resides in the computer’s memory and contains information used by the 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) 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 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.useful services to the client of the object – the script that calls the methods.

Page 72: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 72

Key Points The The document object’s object’s writeln method writes a line of HTML text in the method writes a line of HTML text in the

HTML document. HTML document. Unlike Unlike writeln, , document method method write does not position the output does not position the output

cursor in the HTML document at the beginning of next line of HTML text cursor in the HTML document at the beginning of next line of HTML text after writing its argument.after writing its argument.

Each Each write and and writeln statement resumes writing characters where the last statement resumes writing characters where the last write or writeln stopped writing characters.write or writeln stopped writing characters.

Sometimes it is useful to display information in windows called dialog boxes 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 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 typically used to display important messages to the user who is browsing the Web page. The browser’s Web page. The browser’s window object displays an alert dialog box with object displays an alert dialog box with method method alert. Method . Method alert requires as its argument the string to display.requires as its argument the string to display.

Normally the characters in a string are displayed exactly as they appear 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 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 characters, the next character is combined with the backslash to form an escape sequence. The escape sequenceescape sequence. The escape sequence\n is the newline character. It causes is the newline character. It causes the cursor in the HTML document to move to the beginning of the next line the cursor in the HTML document to move to the beginning of the next line in the dialog box.in the dialog box.

Page 73: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 73

Key Points The keyword The keyword var is used to declare the names of variables. A variable is a 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 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 program. Though not required, all variables should be declared with a name in a a var statement before they are used in a program. statement before they are used in a program.

A variable name can be any valid identifier. An identifier is a series of A variable name can be any valid identifier. An identifier is a series of characters consisting of letters, digits, underscores (_) and dollar signs ($) that characters consisting of letters, digits, underscores (_) and dollar signs ($) that does not contain any spaces.does not contain any spaces.

Programmers often indicate the purpose of each variable in the program by 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 placing a JavaScript comment at the end of each line in the declaration. A single-line comment begins with the characters single-line comment begins with the characters // and terminate at the end of the and terminate at the end of the line. Comments do not cause the browser to perform any action when the script line. Comments do not cause the browser to perform any action when the script is interpreted; rather, comments are ignored by the JavaScript interpreter.is interpreted; rather, comments are ignored by the JavaScript interpreter.

Multiple-line comments begin with delimiter Multiple-line comments begin with delimiter /* and end with delimiter and end with delimiter */. All . All text between the delimiters of the comment is ignored by the JavaScript text between the delimiters of the comment is ignored by the JavaScript interpreter.interpreter.

The The window object’s object’s prompt method displays a dialog into which the user can method displays a dialog into which the user can type a value. The first argument is a message (called a prompt) that directs the 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 user to take a specific action. The optional second argument is the default string to display in the text field.to display in the text field.

Page 74: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 74

Key Points A variable is assigned a value with an assignment statement using the A variable is assigned a value with an assignment statement using the

assignment operator assignment operator =. The. The = operator is called a binary operator because it has operator is called a binary operator because it has two operands.two operands.

Function Function parseInt converts its string argument to an integer. converts its string argument to an integer. JavaScript has a version of the JavaScript has a version of the + operator for string concatenation that enables a operator for string concatenation that enables a

string and a value of another data type (including another string) to be string and a value of another data type (including another string) to be concatenated.concatenated.

When a value is placed in a memory location, this value replaces the previous When a value is placed in a memory location, this value replaces the previous value in that location.value in that location.

Operators in arithmetic expressions are applied in a precise sequence Operators in arithmetic expressions are applied in a precise sequence determined by the rules of operator precedence.determined by the rules of operator precedence.

Parentheses may be used to force the order of evaluation of operators to occur in Parentheses may be used to force the order of evaluation of operators to occur in any sequence desired by the programmer.any sequence desired by the programmer.

Java’s Java’s if structure allows a program to make a decision based on the truth or 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 falsity of a condition. If the condition is met (the condition is true), the statement in the body of thestatement in the body of the if structure is executed. If the condition is not met structure is executed. If the condition is not met (the condition is false), the body statement is not executed.(the condition is false), the body statement is not executed.

Conditions in Conditions in if structures can be formed by using the equality and relational structures can be formed by using the equality and relational operators.operators.

Page 75: JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

JavaScript, by Dr. Khalil 75

Thank you