72
Introduction to Introduction to JavaScript JavaScript INE2720 INE2720 Web Application Software Web Application Software Development Development Essential Materials Essential Materials

Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

  • View
    223

  • Download
    5

Embed Size (px)

Citation preview

Page 1: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

Introduction to Introduction to JavaScriptJavaScript

INE2720INE2720

Web Application Software Web Application Software DevelopmentDevelopment

Essential MaterialsEssential Materials

Page 2: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

22

Outline – Part AOutline – Part A

Overview of JavaScriptOverview of JavaScript– Versions, embedding, commentsVersions, embedding, comments

JavaScript BasicsJavaScript Basics– Variables and Data TypesVariables and Data Types– OperatorsOperators– ExpressionsExpressions

JavaScript Control StructuresJavaScript Control Structures– Conditional StatementsConditional Statements– Looping StatementsLooping Statements

Page 3: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

33

Outline – Part BOutline – Part B

JavaScript Functions and EventsJavaScript Functions and Events– Events HandlersEvents Handlers

Using Object in JavaScriptUsing Object in JavaScript– Object-Oriented ProgrammingObject-Oriented Programming– JavaScript Object ModelJavaScript Object Model– Using Built-In objects (Predefined Using Built-In objects (Predefined

Object)Object)– Custom Object TypesCustom Object Types

Error in JavaScriptError in JavaScript Exception Handling in JavaScriptException Handling in JavaScript

Page 4: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

44

Outline – Part COutline – Part C

Working with Browser ObjectsWorking with Browser Objects– Document Object Model (DOM)Document Object Model (DOM)

Creating Cookies in JavaScriptCreating Cookies in JavaScript– Constructing a standard cookieConstructing a standard cookie– Interaction with the cookieInteraction with the cookie

Introducing DHTMLIntroducing DHTML– Styles and LayersStyles and Layers– Dynamic PositioningDynamic Positioning

Page 5: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

55

Outline – Part DOutline – Part D

JavaScript Application DevelopmentJavaScript Application Development– JavaScript ExampleJavaScript Example– Discuss the execution requirementsDiscuss the execution requirements– How to break down the syntaxHow to break down the syntax

Cool JavaScript SitesCool JavaScript Sites JavaScript and DHTML ReferenceJavaScript and DHTML Reference Hints for JavaScript codingHints for JavaScript coding SummarySummary

Page 6: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

66

IntroductionIntroduction

The growth of the WWW has The growth of the WWW has resulted in a demand for dynamic resulted in a demand for dynamic and interactive web sites.and interactive web sites.

There are many different kinds of There are many different kinds of scripting languages – JavaScript, …scripting languages – JavaScript, …

This lecture aims at This lecture aims at offeringoffering in- in-depth knowledge of JavaScript, depth knowledge of JavaScript, discussingdiscussing the complexity of the complexity of scripting and scripting and studyingstudying various various common examples.common examples.

Page 7: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

77

JavaScript CapabilitiesJavaScript Capabilities

Improve the user interface of a Improve the user interface of a websitewebsite

Make your site easier to navigateMake your site easier to navigate Easily create pop-up alert, windowsEasily create pop-up alert, windows Replace images on a page without Replace images on a page without

reload the pagereload the page Form validationForm validation Many others …Many others …

Page 8: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

88

JavaScript VersionsJavaScript Versions

JavaScript 1.0JavaScript 1.0– Supported by Netscape 2.0 and IE 3.0Supported by Netscape 2.0 and IE 3.0

JavaScript 1.1JavaScript 1.1– Supported by Netscape 3.0 and IE 4.0Supported by Netscape 3.0 and IE 4.0

JavaScript 1.2JavaScript 1.2– Supported by Netscape 4.0 and IE 4.0Supported by Netscape 4.0 and IE 4.0

JavaScript 1.3JavaScript 1.3– Supported by Netscape 4.5 and IE 5.0Supported by Netscape 4.5 and IE 5.0

JavaScript 1.5JavaScript 1.5– Supported by Netscape 6.0 and IE 5.5 and Supported by Netscape 6.0 and IE 5.5 and

laterlater

Page 9: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

99

The Future of The Future of JavaScriptJavaScript ECMA standard brings JavaScript and ECMA standard brings JavaScript and

Jscript together.Jscript together.– ECMA - An International industry ECMA - An International industry

association dedicated to standardize association dedicated to standardize information and communication systems.information and communication systems.

Both Netscape and Microsoft have Both Netscape and Microsoft have pledged that they will support and pledged that they will support and develop JavaScript in the future.develop JavaScript in the future.

It is future-proof, and it is not going to It is future-proof, and it is not going to disappear in the near future. disappear in the near future.

Page 10: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1010

A Simple ScriptA Simple Script<html><html>

<head> <title>First JavaScript Page</title> </head><head> <title>First JavaScript Page</title> </head>

<body><body>

<h1>First JavaScript Page</h1><h1>First JavaScript Page</h1>

<script type="text/javascript"> <script type="text/javascript">

<!--<!--

document.write("<hr>");document.write("<hr>");

document.write("Hello World Wide Web");document.write("Hello World Wide Web");

document.write("<hr>");document.write("<hr>");

--> -->

</script></script>

</body></body>

</html></html>

Page 11: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1111

Embedding JavaScriptEmbedding JavaScript

A <script> tag can be placed either A <script> tag can be placed either within the <head> or <body> tag within the <head> or <body> tag of an HTML document.of an HTML document.

<html><html>

<head><head>

<title>First JavaScript Program</title><title>First JavaScript Program</title>

</head></head>

<body><body>

<script <script languagelanguage==““JavaScriptJavaScript” ” srcsrc==““your_source_file.jsyour_source_file.js””></script>></script>

</body></body>

</html></html>

Page 12: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1212

JavaScript Source FileJavaScript Source File

SRCSRC – specifies the location of an external script – specifies the location of an external script TYPETYPE – specifies the scripting language of the – specifies the scripting language of the

scriptscript LANGUAGELANGUAGE – specifies the scripting language of – specifies the scripting language of

the scriptthe script TYPETYPE and and LANGUAGELANGUAGE have a similar function, we have a similar function, we

use LANGUAGE to specify the language used in use LANGUAGE to specify the language used in the scriptthe script

<script <script languagelanguage==““JavaScriptJavaScript””

srcsrc==““your_source_file.jsyour_source_file.js””></script>></script>

Page 13: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1313

Need for a source fileNeed for a source file

If the JavaScript code is fairly short, If the JavaScript code is fairly short, you are recommended to include the you are recommended to include the code in the HTML document.code in the HTML document.

To add clarity to an HTML document.To add clarity to an HTML document. To share JavaScript code across To share JavaScript code across

multiple HTML documents.multiple HTML documents. To help you hide your JavaScript code.To help you hide your JavaScript code.

– Spent lot of time for JavaScript coding.Spent lot of time for JavaScript coding.– Viewer can only see the location of the Viewer can only see the location of the

source file but not the contents.source file but not the contents.

Page 14: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1414

Hide JavaScript from Hide JavaScript from incompatible browsersincompatible browsers

Not all browsers support JavaScript.Not all browsers support JavaScript. E.g. NN1, IE2, character-based lynx.E.g. NN1, IE2, character-based lynx.

<script <script languagelanguage==““JavaScriptJavaScript””>>

<!– begin hiding JavaScript<!– begin hiding JavaScript

// single-line comment// single-line comment, , /* … */ multiple-line comment/* … */ multiple-line comment

End hiding JavaScript -->End hiding JavaScript -->

</script></script>

<noscript><noscript>

Your browser does not support JavaScript.Your browser does not support JavaScript.

</noscript></noscript>

Page 15: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1515

JavaScript confusionJavaScript confusion

JavaScriptJavaScript JavaJavaInterpreted by the client-side Interpreted by the client-side computercomputer

Compiled on the server before Compiled on the server before executed on the client machineexecuted on the client machine

Dynamic binding, object Dynamic binding, object references are checked at references are checked at runtimeruntime

Static binding, object references Static binding, object references must exist at compile timemust exist at compile time

No need to declare data typesNo need to declare data types Data types must be declaredData types must be declared

Code is embedded in HTMLCode is embedded in HTML Code is not integrated in HTMLCode is not integrated in HTML

Limited by the browser Limited by the browser functionalityfunctionality

Java applications are standaloneJava applications are standalone

Can access browser objectsCan access browser objects Java has no access to browser Java has no access to browser objectsobjects

Page 16: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1616

Using the alert() Using the alert() MethodMethod

It is the easiest methods to use amongst It is the easiest methods to use amongst alert(), prompt() and confirm().alert(), prompt() and confirm().

You can use it to display textual You can use it to display textual information to the user (simple and information to the user (simple and concise).concise).

The user can simply click “OK” to close it.The user can simply click “OK” to close it.

<head><head>

<script <script languagelanguage==““JavaScriptJavaScript””>>

alert(“An alert triggered by JavaScript”);alert(“An alert triggered by JavaScript”);

</script></script>

</head></head>

Page 17: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1717

Using the confirm() Using the confirm() MethodMethod

This box is used to give the user a choice This box is used to give the user a choice either OK or Cancel.either OK or Cancel.

It is very similar to the “alert()” method.It is very similar to the “alert()” method. You can also put your message in the You can also put your message in the

method.method.

<head><head>

<script <script languagelanguage==““JavaScriptJavaScript””>>

confirm(“Are you happy with the class?”);confirm(“Are you happy with the class?”);

</script></script>

</head></head>

Page 18: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1818

Using the alert() Using the alert() MethodMethod

This is the only one that allows the This is the only one that allows the user to type in his own response to the user to type in his own response to the specific question.specific question.

You can give a default value to avoid You can give a default value to avoid displaying “undefined”.displaying “undefined”.

<head><head>

<script <script languagelanguage==““JavaScriptJavaScript””>>

prompt(“What is your student id number?”);prompt(“What is your student id number?”);

prompt(“What is your name?”,”No name”);prompt(“What is your name?”,”No name”);

</script></script>

</head></head>

Page 19: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

1919

Three methodsThree methods

<script <script language="JavaScript">language="JavaScript">

alert("This is an Alert alert("This is an Alert method");method");

confirm("Are you OK?");confirm("Are you OK?");

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

prompt("How old are prompt("How old are you?","20");you?","20");

</script></script>

Page 20: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2020

VariablesVariables

JavaScript allows you to declare and JavaScript allows you to declare and use variables to store values.use variables to store values.

How to assign a name to a variable?How to assign a name to a variable?– Include uppercase and lowercase lettersInclude uppercase and lowercase letters– Digits from 0 through 9Digits from 0 through 9– The underscore _ and the dollar sign $The underscore _ and the dollar sign $– No space and punctuation charactersNo space and punctuation characters– First character must be alphabetic letter or First character must be alphabetic letter or

underscore – 99Total?, 012345number?, …underscore – 99Total?, 012345number?, …– Case-sensitiveCase-sensitive– No reserved words or keywordsNo reserved words or keywords

Page 21: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2121

Which one is legal?Which one is legal?

My_variableMy_variable

$my_variable$my_variable

1my_example1my_example

_my_variable_my_variable

@my_variable@my_variable

My_variable_examplMy_variable_examplee

++my_variable++my_variable

%my_variable%my_variable

#my_variable#my_variable

~my_variable~my_variable

myVariableExamplemyVariableExample

Legal

Illegal

Page 22: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2222

Variable on-the-flyVariable on-the-fly

We should use “var” because it is more We should use “var” because it is more easy to keep track of the variables.easy to keep track of the variables.

<head><head>

<script <script languagelanguage==““JavaScriptJavaScript””>>

var id;var id;

id = prompt(“What is your student id number?”);id = prompt(“What is your student id number?”);

alert(id);alert(id);

name = prompt(“What is your name?”,”No name = prompt(“What is your name?”,”No name”);name”);

alert(name);alert(name);

</script></script>

</head></head>

Variable declaration

Page 23: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2323

Data TypesData Types

JavaScript allows the same variable to contain JavaScript allows the same variable to contain different types of data values.different types of data values.

Primitive data typesPrimitive data types– NumberNumber: integer & floating-point numbers: integer & floating-point numbers– BooleanBoolean: logical values “true” or “false”: logical values “true” or “false”– StringString: a sequence of alphanumeric characters: a sequence of alphanumeric characters

Composite data types (or Complex data types)Composite data types (or Complex data types)– ObjectObject: a named collection of data: a named collection of data– ArrayArray: a sequence of values: a sequence of values

Special data typesSpecial data types– NullNull: an initial value is assigned: an initial value is assigned– UndefinedUndefined: the variable has been created by not yet : the variable has been created by not yet

assigned a valueassigned a value

Page 24: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2424

Numeric Data TypesNumeric Data Types

It is an important part of any It is an important part of any programming language for doing programming language for doing arithmetic calculations.arithmetic calculations.

JavaScript supports: JavaScript supports: – Integers:Integers: A positive or negative A positive or negative

number with no decimal places.number with no decimal places. Ranged from –2Ranged from –25353 to 2 to 25353

– Floating-point numbers:Floating-point numbers: usually usually written in exponential notation. written in exponential notation. 3.1415…, 2.0e113.1415…, 2.0e11

Page 25: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2525

Integer and Floating-Integer and Floating-point number examplepoint number example<script <script languagelanguage==““JavaScriptJavaScript””>>

var integerVar = 100;var integerVar = 100;

var floatingPointVar = 3.0e10;var floatingPointVar = 3.0e10;

// floating-point number 30000000000// floating-point number 30000000000

document.write(integerVar);document.write(integerVar);

document.write(floatingPointVar);document.write(floatingPointVar);

</script></script>

The integer 100 and the number The integer 100 and the number 30,000,000,000 will be appeared in the 30,000,000,000 will be appeared in the browser window.browser window.

Page 26: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2626

Boolean ValuesBoolean Values

A Boolean value is a logical value A Boolean value is a logical value of either true or false. (yes/no, of either true or false. (yes/no, on/off)on/off)

Often used in decision making and Often used in decision making and data comparison.data comparison.

In JavaScript, you can use the In JavaScript, you can use the words “true” and “false” directly words “true” and “false” directly to indicate Boolean values.to indicate Boolean values.

Named by the 19Named by the 19thth century century mathematician “George Boole”.mathematician “George Boole”.

Page 27: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2727

Boolean value exampleBoolean value example

The expression is converted to The expression is converted to – (1*10 + 0*7) = 10(1*10 + 0*7) = 10

They are automatically converted.They are automatically converted.

<head><head>

<script <script languagelanguage==““JavaScriptJavaScript””>>

var result;var result;

result = (true*10 + false*7);result = (true*10 + false*7);

alert(“true*10 + false*7 = “, result);alert(“true*10 + false*7 = “, result);

</script></script>

</head></head>

Page 28: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2828

StringsStrings

A string variable can store a sequence A string variable can store a sequence of alphanumeric characters, spaces of alphanumeric characters, spaces and special characters.and special characters.

String can also be enclosed in single String can also be enclosed in single quotation marks (‘) or in double quotation marks (‘) or in double quotation marks (“).quotation marks (“).

What is the data type of “100”?What is the data type of “100”?– String but not number typeString but not number type

Pay attention to the special Pay attention to the special characters.characters.

Page 29: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

2929

Strings exampleStrings example

Unlike Java and C, JavaScript does Unlike Java and C, JavaScript does not have a single character (char) not have a single character (char) data type.data type.

<head><head>

<script <script languagelanguage==““JavaScriptJavaScript””>>

document.write(“This is a string.”);document.write(“This is a string.”);

document.write(“This string contains ‘quote’.”);document.write(“This string contains ‘quote’.”);

var myString = “My testing string”;var myString = “My testing string”;

alert(myString);alert(myString);

</script></script>

</head></head>

Page 30: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3030

typeof operatortypeof operator

It is an unary operator.It is an unary operator.– Return either: Number, string, Boolean, Return either: Number, string, Boolean,

object, function, undefined, nullobject, function, undefined, null

<head><head>

<script <script languagelanguage==““JavaScriptJavaScript””>>

var x = “hello”, y;var x = “hello”, y;

alert(“Variable x value is “ + typeof(x));alert(“Variable x value is “ + typeof(x));

alert(“Variable y value is “ + typeof(y));alert(“Variable y value is “ + typeof(y));

alert(“Variable x value is “ + typeof(z));alert(“Variable x value is “ + typeof(z));

</script></script>

</head></head>

Page 31: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3131

What is an Object?What is an Object?

An object is a thing, anything, just as An object is a thing, anything, just as things in the real world. things in the real world. – E.g. (cars, dogs, money, books, … )E.g. (cars, dogs, money, books, … )

In the web browser, objects are the In the web browser, objects are the browser window itself, forms, buttons, text browser window itself, forms, buttons, text boxes, …boxes, …

Methods are things that objects can do.Methods are things that objects can do.– Cars can move, dogs can bark.Cars can move, dogs can bark.– Window object can alert the user “alert()”.Window object can alert the user “alert()”.

All objects have properties.All objects have properties.– Cars have wheels, dogs have fur.Cars have wheels, dogs have fur.– Browser has a name and version number.Browser has a name and version number.

Page 32: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3232

ArrayArray

An Array contains a set of data An Array contains a set of data represented by a single variable represented by a single variable name.name.

Arrays in JavaScript are represented Arrays in JavaScript are represented by the Array Object, we need to “new by the Array Object, we need to “new Array()” to construct this object.Array()” to construct this object.

The first element of the array is The first element of the array is “Array[0]” until the last one Array[i-1].“Array[0]” until the last one Array[i-1].

E.g. myArray = new Array(5)E.g. myArray = new Array(5)– We have myArray[0,1,2,3,4].We have myArray[0,1,2,3,4].

Page 33: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3333

Array ExampleArray Example

<script <script languagelanguage==““JavaScriptJavaScript””>>

Car = new Array(3);Car = new Array(3);

Car[0] = “Ford”;Car[0] = “Ford”;

Car[1] = “Toyota”;Car[1] = “Toyota”;

Car[2] = “Honda”;Car[2] = “Honda”;

document.write(Car[0] + “<br>”);document.write(Car[0] + “<br>”);

document.write(Car[1] + “<br>”);document.write(Car[1] + “<br>”);

document.write(Car[2] + “<br>”);document.write(Car[2] + “<br>”);

</script></script> You can also declare arrays with variable length.You can also declare arrays with variable length.

– arrayName = new Array();arrayName = new Array();– Length = 0, allows automatic extension of the length.Length = 0, allows automatic extension of the length.– Car[9] = “Ford”; Car[99] = “Honda”;Car[9] = “Ford”; Car[99] = “Honda”;

Page 34: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3434

Null & UndefinedNull & Undefined

An “undefined” value is returned An “undefined” value is returned when you attempt to use a variable when you attempt to use a variable that has not been defined or you that has not been defined or you have declared but you forgot to have declared but you forgot to provide with a value.provide with a value.

Null refers to “nothing”Null refers to “nothing” You can declare and define a You can declare and define a

variable as “null” if you want variable as “null” if you want absolutely nothing in it, but you just absolutely nothing in it, but you just don’t want it to be “undefined”.don’t want it to be “undefined”.

Page 35: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3535

Null & Undefined Null & Undefined exampleexample<html><html>

<head><head>

<title> Null and Undefined example </title><title> Null and Undefined example </title>

<script language=“JavaScript”><script language=“JavaScript”>

var test1, test2 = null;var test1, test2 = null;

alert(“No value assigned to the variable” + test1);alert(“No value assigned to the variable” + test1);

alert(“A null value was assigned” + test2);alert(“A null value was assigned” + test2);

</script></script>

</head></head>

<body> … </body><body> … </body>

</html></html>

Page 36: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3636

JavaScript Special JavaScript Special CharactersCharacters

CharacterCharacter MeaningMeaning

\b\b BackspaceBackspace

\f\f Form feedForm feed

\t\t Horizontal tabHorizontal tab

\n\n New lineNew line

\r\r Carriage returnCarriage return

\\\\ BackslashBackslash

\’\’ Single quoteSingle quote

\”\” Double quoteDouble quote

Page 37: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3737

Break Time – 10 Break Time – 10 minutesminutes

Page 38: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3838

ExpressionsExpressions

It is a set of literals, variables, It is a set of literals, variables, operators that merge and operators that merge and evaluate to a single value.evaluate to a single value.– Left_operandLeft_operand operatoroperator right_operandright_operand

By using different operators, you By using different operators, you can create the following can create the following expressions.expressions.– Arithmetic, logicalArithmetic, logical– String and conditional expressions.String and conditional expressions.

Page 39: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

3939

OperatorsOperators

Arithmetic operatorsArithmetic operators Logical operatorsLogical operators Comparison operatorsComparison operators String operatorsString operators Bit-wise operatorsBit-wise operators Assignment operatorsAssignment operators Conditional operatorsConditional operators

Page 40: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4040

Arithmetic operatorsArithmetic operators

left_operand “operator” right_operandleft_operand “operator” right_operand

OperatoOperatorr

NameName DescriptionDescription ExampleExample

++ AdditionAddition Adds the operandsAdds the operands 3 + 53 + 5

-- SubtractionSubtraction Subtracts the right operand Subtracts the right operand from the left operandfrom the left operand

5 - 35 - 3

** MultiplicatiMultiplicationon

Multiplies the operandsMultiplies the operands 3 * 53 * 5

// DivisionDivision Divides the left operand by Divides the left operand by the right operandthe right operand

30 / 530 / 5

%% ModulusModulus Calculates the remainderCalculates the remainder 20 % 520 % 5

Page 41: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4141

Unary Arithmetic Unary Arithmetic OperatorsOperators Binary operators take two operands.Binary operators take two operands. Unary type operators take only one operand.Unary type operators take only one operand. Which one add value first, and then assign value to the variable?Which one add value first, and then assign value to the variable?

NameName ExampleExample

Post Incrementing operatorPost Incrementing operator Counter++Counter++

Post Decrementing operatorPost Decrementing operator Counter--Counter--

Pre Incrementing operatorPre Incrementing operator ++counter++counter

Pre Decrementing operatorPre Decrementing operator --counter--counter

Page 42: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4242

Logical operatorsLogical operators

Used to perform Boolean operations on Boolean Used to perform Boolean operations on Boolean operandsoperands

OperatoOperatorr

NameName DescriptionDescription ExampleExample

&&&& Logical andLogical and Evaluate to “true” when Evaluate to “true” when both operands are trueboth operands are true

3>2 && 3>2 && 5<25<2

|||| Logical orLogical or Evaluate to “true when Evaluate to “true when either operand is trueeither operand is true

3>1 || 2>53>1 || 2>5

!! Logical notLogical not Evaluate to “true” when Evaluate to “true” when the operand is falsethe operand is false

5 != 35 != 3

Page 43: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4343

Comparison operatorsComparison operators

Used to compare two numerical valuesUsed to compare two numerical values

OperatOperatoror

NameName DescriptionDescription ExampleExample

==== EqualEqual Perform type conversion before checking the Perform type conversion before checking the equalityequality

““5” == 55” == 5

====== Strictly equalStrictly equal No type conversion before testingNo type conversion before testing ““5” === 5” === 55

!=!= Not equalNot equal ““true” when both operands are not equaltrue” when both operands are not equal 4 != 24 != 2

!==!== Strictly not Strictly not equalequal

No type conversion before testing No type conversion before testing nonequalitynonequality

5 !== 5 !== “5”“5”

>> Greater thanGreater than ““true” if left operand is greater than right true” if left operand is greater than right operandoperand

2 > 52 > 5

<< Less thanLess than ““true” if left operand is less than right true” if left operand is less than right operandoperand

3 < 53 < 5

>=>= Greater than or Greater than or equalequal

““true” if left operand is greater than or equal true” if left operand is greater than or equal to the right operandto the right operand

5 >= 25 >= 2

<=<= Less than or Less than or equalequal

““true” if left operand is less than or equal to true” if left operand is less than or equal to the right operandthe right operand

5 <= 25 <= 2

Page 44: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4444

Strict Equality Strict Equality OperatorsOperators

Surprised that outcome1 is True!Surprised that outcome1 is True! JavaScript tries very hard to resolve JavaScript tries very hard to resolve

numeric and string differences.numeric and string differences.

<script language=“JavaScript”><script language=“JavaScript”>

var currentWord=“75”;var currentWord=“75”;

var currentValue=75;var currentValue=75;

var outcome1=(currentWord == currentValue);var outcome1=(currentWord == currentValue);

var outcome2=(currentWord === currentValue);var outcome2=(currentWord === currentValue);

alert(“outcome1: “ + outcome1 + “ : outcome2: “ + alert(“outcome1: “ + outcome1 + “ : outcome2: “ + outcome2);outcome2);

</script></script>

Page 45: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4545

String operatorString operator

JavaScript only supports one string JavaScript only supports one string operator for joining two strings.operator for joining two strings.

OperatoOperatorr

NameName DescriptionDescription Return Return valuevalue

++ String String concatenatioconcatenatio

nn

Joins two stringsJoins two strings ““HelloWorldHelloWorld””

<script language=“JavaScript”><script language=“JavaScript”>

var myString = “”;var myString = “”;

myString = “Hello” + “World”;myString = “Hello” + “World”;

alert(myString);alert(myString);

</script></script>

Page 46: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4646

Bit Manipulation Bit Manipulation operatorsoperators Perform operations on the bit representation Perform operations on the bit representation

of a value, such as shift left or right.of a value, such as shift left or right.

OperatorOperator NameName DescriptionDescription

&& Bitwise ANDBitwise AND Examines each bit positionExamines each bit position

|| Bitwise ORBitwise OR If either bit of the operands is 1, the result If either bit of the operands is 1, the result will be 1will be 1

^̂ Bitwise XORBitwise XOR Set the result bit, only if either bit is 1, but Set the result bit, only if either bit is 1, but not bothnot both

<<<< Bitwise left Bitwise left shiftshift

Shifts the bits of an expression to the leftShifts the bits of an expression to the left

>>>> Bitwise Bitwise signed right signed right

shiftshift

Shifts the bits to the right, and maintains the Shifts the bits to the right, and maintains the signsign

>>>>>> Bitwise zero-Bitwise zero-fill right shiftfill right shift

Shifts the bits of an expression to rightShifts the bits of an expression to right

Page 47: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4747

Assignment operatorsAssignment operators

Used to assign values to variablesUsed to assign values to variables

OperatoOperatorr

DescriptionDescription ExampleExample

== Assigns the value of the right operand to the left Assigns the value of the right operand to the left operandoperand

A = 2A = 2

+=+= Add the operands and assigns the result to the left Add the operands and assigns the result to the left operandoperand

A += 5A += 5

-=-= Subtracts the operands and assigns the result to Subtracts the operands and assigns the result to the left operandthe left operand

A -= 5A -= 5

*=*= Multiplies the operands and assigns the result to Multiplies the operands and assigns the result to the left operandthe left operand

A *= 5A *= 5

/=/= Divides the left operands by the right operand and Divides the left operands by the right operand and assigns the result to the left operandassigns the result to the left operand

A /= 5A /= 5

%=%= Assigns the remainder to the left operandAssigns the remainder to the left operand A %= 2A %= 2

Page 48: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4848

The most common The most common problemproblem

Don’t mix the comparison Don’t mix the comparison operator and the assignment operator and the assignment operator. operator.

double equal sign (==) and the double equal sign (==) and the equal operator (=)equal operator (=)

<script language=“JavaScript”><script language=“JavaScript”>

if (alpha = beta) { … }if (alpha = beta) { … }

if (alpha == beta) { … }if (alpha == beta) { … }

</script></script>

Page 49: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

4949

Order of PrecedenceOrder of PrecedencePrecedencPrecedenc

eeOperatorOperator

11 Parentheses, function callsParentheses, function calls

22 , ~, -, ++, --, new, void, delete, ~, -, ++, --, new, void, delete

33 *, /, %*, /, %

44 +, -+, -

55 <<, >>, >>><<, >>, >>>

66 <, <=, >, >=<, <=, >, >=

77 ==, !=, ===, !====, !=, ===, !==

88 &&

99 ^̂

1010 ||

1111 &&&&

1212 ||||

1313 ?:?:

1414 =, +=, -=, *=, …=, +=, -=, *=, …

1515 The comma (,) operatorThe comma (,) operator

Page 50: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5050

Precedence ExamplePrecedence Example

Value = (19 % 4) / 1 – 1 - !Value = (19 % 4) / 1 – 1 - !falsefalse

Value = 3 / 1 – 1 - !falseValue = 3 / 1 – 1 - !false

Value = 3 / 1 – 1 - trueValue = 3 / 1 – 1 - true

Value = 3 – 1 - trueValue = 3 – 1 - true

Value = 3 – 2Value = 3 – 2

Value = 1Value = 1

Page 51: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5151

Scope of a VariableScope of a Variable

When you use a variable in a When you use a variable in a JavaScript program that uses JavaScript program that uses functions.functions.

A global scope variable is one A global scope variable is one that is declared outside a function that is declared outside a function and is accessible in any part of and is accessible in any part of your program.your program.

A local variable is declared inside A local variable is declared inside a function and stops existing a function and stops existing when the function ends.when the function ends.

Page 52: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5252

Example of variable, data Example of variable, data typestypes<html><head><title> Billing System of Web Shoppe </title></head><body><html><head><title> Billing System of Web Shoppe </title></head><body>

<h1 align="center"> Billing System of Web Shoppe </h1><h1 align="center"> Billing System of Web Shoppe </h1>

<script language="JavaScript"><script language="JavaScript">

firstCustomer = new Array();firstCustomer = new Array();

billDetails = new Array(firstCustomer);billDetails = new Array(firstCustomer);

var custName, custDob, custAddress, custCity, custPhone;var custName, custDob, custAddress, custCity, custPhone;

var custAmount, custAmountPaid, custBalAmount;var custAmount, custAmountPaid, custBalAmount;

custName=prompt("Enter the first customer's name:", "");custName=prompt("Enter the first customer's name:", "");

custDob=prompt("Enter the first customer's date of birth:", "");custDob=prompt("Enter the first customer's date of birth:", "");

custAddress=prompt("Enter the first customer's address:", "");custAddress=prompt("Enter the first customer's address:", "");

custPhone=prompt("Enter the first customer's phone number:", "");custPhone=prompt("Enter the first customer's phone number:", "");

custAmount=prompt("Enter the total bill amount of the first customer:", "");custAmount=prompt("Enter the total bill amount of the first customer:", "");

custAmountPaid=prompt("Enter the amount paid by the first customer:", "");custAmountPaid=prompt("Enter the amount paid by the first customer:", "");

custBalAmount = custAmount - custAmountPaid;custBalAmount = custAmount - custAmountPaid;

firstCustomer[0]=custName;firstCustomer[0]=custName;

firstCustomer[1]=custDob;firstCustomer[1]=custDob;

firstCustomer[2]=custAddress;firstCustomer[2]=custAddress;

firstCustomer[3]=custPhone;firstCustomer[3]=custPhone;

firstCustomer[4]=custBalAmount;firstCustomer[4]=custBalAmount;

document.write("<B>" + "You have entered the following details for first customer:" + "<BR>");document.write("<B>" + "You have entered the following details for first customer:" + "<BR>");

document.write("Name: " + billDetails[0][0] + "<BR>");document.write("Name: " + billDetails[0][0] + "<BR>");

document.write("Date of Birth: " + billDetails[0][1] + "<BR>");document.write("Date of Birth: " + billDetails[0][1] + "<BR>");

document.write("Address: " + billDetails[0][2] + "<BR>");document.write("Address: " + billDetails[0][2] + "<BR>");

document.write("Phone: " + billDetails[0][3] + "<BR>");document.write("Phone: " + billDetails[0][3] + "<BR>");

(custBalAmount == 0) ? document.write("Amount Outstanding: " + custBalAmount):document.write("No (custBalAmount == 0) ? document.write("Amount Outstanding: " + custBalAmount):document.write("No amount due")amount due")

</script></body></html></script></body></html>

Page 53: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5353

Output of the codeOutput of the code

Page 54: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5454

Conditional StatementConditional Statement

““if” statementif” statement ““if … else” statementif … else” statement ““else if” statementelse if” statement ““if/if … else” statementif/if … else” statement ““switch” statementswitch” statement

Page 55: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5555

““if” statementif” statement

It is the main conditional statement in It is the main conditional statement in JavaScript.JavaScript.

The keyword “if” always appears in The keyword “if” always appears in lowercase.lowercase.

The condition yields a logical true or The condition yields a logical true or false value.false value.

The condition is true, statements are The condition is true, statements are executed.executed.

if if ((conditioncondition)) {{ statements;statements; }}

Page 56: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5656

““if” statement if” statement exampleexample

<script language=“JavaScript”><script language=“JavaScript”>

var chr = “”;var chr = “”;

……

if (chr == ‘A’ || chr == ‘O’) if (chr == ‘A’ || chr == ‘O’) {{

document.write(“Vowel variable”);document.write(“Vowel variable”);

}}

</script></script>

“||” operator - increase the speed of the script

Page 57: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5757

““if … else” statementif … else” statement

You can include an “else” clause You can include an “else” clause in an if statement when you want in an if statement when you want to execute some statements if to execute some statements if the condition is false.the condition is false.

if if ((conditioncondition)) {{ statements;statements; }}

elseelse { { statements;statements; } }

Page 58: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5858

Ternary Shortcut Ternary Shortcut (concise)(concise)

<script language=“JavaScript”><script language=“JavaScript”>

If (3 > 2) {If (3 > 2) {

alert(“True”);alert(“True”);

} else {} else {

alert(“False”);alert(“False”);

}}

(3 > 2) ? alert(“True”) : alert(“False”);(3 > 2) ? alert(“True”) : alert(“False”);

</script></script>

Substitute for a simple “if/else” statement.Substitute for a simple “if/else” statement.

Page 59: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

5959

““else if” statementelse if” statement

Allows you to test for multiple Allows you to test for multiple expression for one true value and expression for one true value and executes a particular block of executes a particular block of code.code.

if if ((conditioncondition)) {{ statement;statement; }}

else ifelse if ((conditioncondition)) {{ statement;statement; }}

elseelse { { statement;statement; }}

Page 60: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6060

““if/if…else” statement if/if…else” statement exampleexample

<script language=“JavaScript”><script language=“JavaScript”>

var chr;var chr;

chr = prompt(“Please enter a character : “,””);chr = prompt(“Please enter a character : “,””);

if (chr >= ‘A’){if (chr >= ‘A’){

if (chr <= ‘Z’)if (chr <= ‘Z’)

alert(“Uppercase”);alert(“Uppercase”);

else if (chr >= ‘a’){else if (chr >= ‘a’){

alert(“Lowercase”);alert(“Lowercase”);

}}

}}

</script></script>

Page 61: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6161

““switch” statementswitch” statement

Allows you to merge several Allows you to merge several evaluation tests of the same variable evaluation tests of the same variable into a single block of statements. into a single block of statements.

switch switch ((expressionexpression)) {{

casecase label1:label1:

statements; statements; break;break;

default:default:

statements;statements;

}}

Page 62: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6262

““switch” statement switch” statement exampleexample

<script language=“JavaScript”><script language=“JavaScript”>

var chr;var chr;

chr = prompt(“Pls enter a character in lowercase:”,””);chr = prompt(“Pls enter a character in lowercase:”,””);

switch(chr){switch(chr){

case ‘a’ :case ‘a’ :

alert(“Vowel a”); break;alert(“Vowel a”); break;

case ‘e’ :case ‘e’ :

alert(“Vowel e”); break;alert(“Vowel e”); break;

default :default :

alert(“Not a vowel”);alert(“Not a vowel”);

}}

</script></script>

Page 63: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6363

Looping StatementLooping Statement

““for” Loopsfor” Loops ““for/in” Loopsfor/in” Loops ““while” Loopswhile” Loops ““do … while” Loopsdo … while” Loops ““break” statementbreak” statement ““continue” statementcontinue” statement

Page 64: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6464

““for” statementfor” statement

One of the most used and familiar One of the most used and familiar loops is the for loop.loops is the for loop.

It iterates through a sequence of It iterates through a sequence of statements for a number of times statements for a number of times controlled by a condition.controlled by a condition.

The change_exp determines how much The change_exp determines how much has been added or subtracted from the has been added or subtracted from the counter variable.counter variable.

for for ((initial_expression; initial_expression; test_exp;test_exp; change_expchange_exp))

{{ statements; statements; }}

Page 65: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6565

““for” statement for” statement exampleexample

Display the square of numbersDisplay the square of numbers Output: 1 4 9 16 25 36 49 64 81 100Output: 1 4 9 16 25 36 49 64 81 100

<script language=“JavaScript”><script language=“JavaScript”>

var counter;var counter;

forfor ( (counter = 1counter = 1; counter <= 10; ; counter <= 10; counter++counter++))

{{

document.write(counter*counter + “ “);document.write(counter*counter + “ “);

}}

</script></script>

Page 66: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6666

““for/in” statementfor/in” statement

When the for/in statement is used, the When the for/in statement is used, the counter and termination are counter and termination are determined by the length of the object.determined by the length of the object.

The statement begins with 0 as the The statement begins with 0 as the initial value of the counter variable, initial value of the counter variable, terminates with all the properties of terminates with all the properties of the objects have been exhausted.the objects have been exhausted.– E.g. array E.g. array no more elements found no more elements found

for for (counter_variable in object)(counter_variable in object)

{{ statements; statements; }}

Page 67: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6767

““for/in” statement for/in” statement exampleexample

<script language=“JavaScript”><script language=“JavaScript”>

var book; var book; (What is the difference if “var book=“”;)(What is the difference if “var book=“”;)

var booklist = new Array(“Chinese”, “English”, var booklist = new Array(“Chinese”, “English”, “Jap”);“Jap”);

for (for (var countervar counter in in booklistbooklist) {) {

book += booklist[counter] + “ “;book += booklist[counter] + “ “;

}}

alert(book);alert(book);

</script></script>

Page 68: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6868

““while” statementwhile” statement

The while loop begins with a termination The while loop begins with a termination condition and keeps looping until the condition and keeps looping until the termination condition is met.termination condition is met.

The counter variable is managed by the The counter variable is managed by the context of the statements inside the curly context of the statements inside the curly braces.braces.

initial value declaration;initial value declaration;

while while ((conditioncondition)) {{

statements;statements;

increment/decrement statement;increment/decrement statement;

}}

Page 69: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

6969

““While” statement While” statement exampleexample

<html><html>

<head><head>

<title>While loop example</title><title>While loop example</title>

<script language=“JavaScript”><script language=“JavaScript”>

var counter = 100;var counter = 100;

var numberlist = “”;var numberlist = “”;

whilewhile ((counter > 0counter > 0) {) {

numberlist += “Number “ + counter + “<br>”;numberlist += “Number “ + counter + “<br>”;

counter -= 10;counter -= 10;

}}

document.write(numberlist);document.write(numberlist);

</script> <body> … </body> </script> <body> … </body>

</html></html>

Page 70: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

7070

““do … while” do … while” statementstatement

The do/while loop always The do/while loop always executes statements in the loop executes statements in the loop in the first iteration of the loop.in the first iteration of the loop.

The termination condition is The termination condition is placed at the bottom of the loop.placed at the bottom of the loop.

do do {{

statements; statements;

counter increment/decrement;counter increment/decrement;

}} while while ((termination termination conditioncondition))

Page 71: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

7171

Example of Flow Example of Flow ControlControl

Page 72: Introduction to JavaScript INE2720 Web Application Software Development Essential Materials

INE2720 – Web Application Software INE2720 – Web Application Software DevelopmentDevelopment

All copyrights reserved by C.C. Cheung All copyrights reserved by C.C. Cheung 2003.2003.

7272

ReferencesReferences

Deitel: Chapter 7, 8, 9, 11Deitel: Chapter 7, 8, 9, 11 CWP: Chapter 24CWP: Chapter 24 Making use of JavaScriptMaking use of JavaScript SAMS JavaScriptSAMS JavaScript

The End.The End. Thank you for patience!Thank you for patience!