You are on page 1of 36

Introduction to JavaScript

INE2720
Web Application Software Development

Essential Materials

Outline – Part A

 Overview of JavaScript
– Versions, embedding, comments
 JavaScript Basics
– Variables and Data Types
– Operators
– Expressions
 JavaScript Control Structures
– Conditional Statements
– Looping Statements
INE2720 – Web Application Software Development 2 All copyrights reserved by C.C. Cheung 2003.

1
Outline – Part B

 JavaScript Functions and Events


– Events Handlers
 Using Object in JavaScript
– Object-
Object-Oriented Programming
– JavaScript Object Model
– Using Built-
Built-In objects (Predefined Object)
– Custom Object Types
 Error in JavaScript
 Exception Handling in JavaScript
INE2720 – Web Application Software Development 3 All copyrights reserved by C.C. Cheung 2003.

Outline – Part C

 Working with Browser Objects


– Document Object Model (DOM)
 Creating Cookies in JavaScript
– Constructing a standard cookie
– Interaction with the cookie
 Introducing DHTML
– Styles and Layers
– Dynamic Positioning
INE2720 – Web Application Software Development 4 All copyrights reserved by C.C. Cheung 2003.

2
Outline – Part D

 JavaScript Application Development


– JavaScript Example
– Discuss the execution requirements
– How to break down the syntax
 Cool JavaScript Sites
 JavaScript and DHTML Reference
 Hints for JavaScript coding
 Summary
INE2720 – Web Application Software Development 5 All copyrights reserved by C.C. Cheung 2003.

Introduction

 The growth of the WWW has resulted


in a demand for dynamic and
interactive web sites.
 There are many different kinds of
scripting languages – JavaScript, …
 This lecture aims at offering in-
in-depth
knowledge of JavaScript, discussing
the complexity of scripting and
studying various common examples.
INE2720 – Web Application Software Development 6 All copyrights reserved by C.C. Cheung 2003.

3
JavaScript Capabilities

 Improve the user interface of a


website
 Make your site easier to navigate
 Easily create pop-
pop-up alert, windows
 Replace images on a page without
reload the page
 Form validation
 Many others …
INE2720 – Web Application Software Development 7 All copyrights reserved by C.C. Cheung 2003.

JavaScript Versions
 JavaScript 1.0
– Supported by Netscape 2.0 and IE 3.0
 JavaScript 1.1
– Supported by Netscape 3.0 and IE 4.0
 JavaScript 1.2
– Supported by Netscape 4.0 and IE 4.0
 JavaScript 1.3
– Supported by Netscape 4.5 and IE 5.0
 JavaScript 1.5
– Supported by Netscape 6.0 and IE 5.5 and later
INE2720 – Web Application Software Development 8 All copyrights reserved by C.C. Cheung 2003.

4
The Future of JavaScript

 ECMA standard brings JavaScript and Jscript


together.
– ECMA - An International industry association
dedicated to standardize information and
communication systems.
 Both Netscape and Microsoft have pledged
that they will support and develop
JavaScript in the future.
 It is future-
future-proof, and it is not going to
disappear in the near future. 
INE2720 – Web Application Software Development 9 All copyrights reserved by C.C. Cheung 2003.

A Simple Script
<html>
<head> <title>First JavaScript Page</title> </head>
<body>
<h1>First JavaScript Page</h1>
<script type="text/javascript
type="text/javascript">
">
<!--
<!--
document.write("<hr>");
document.write("Hello World Wide Web");
document.write("<hr>");
-->
-->
</script>
</body>
</html>

INE2720 – Web Application Software Development 10 All copyrights reserved by C.C. Cheung 2003.

5
Embedding JavaScript
<html>
<head>
<title>First JavaScript Program</title>
</head>
<body>
<script language=
language=“JavaScript”
JavaScript” src=
src=“your_source_file.js”
your_source_file.js”></script>
</body>
</html>

 A <script> tag can be placed either


within the <head> or <body> tag of
an HTML document.
INE2720 – Web Application Software Development 11 All copyrights reserved by C.C. Cheung 2003.

JavaScript Source File

<script language=
language=“JavaScript”
JavaScript”
src=
src=“your_source_file.js”
your_source_file.js”></script>

 SRC – specifies the location of an external script


 TYPE – specifies the scripting language of the script
 LANGUAGE – specifies the scripting language of the
script
 TYPE and LANGUAGE have a similar function, we
use LANGUAGE to specify the language used in the
script
INE2720 – Web Application Software Development 12 All copyrights reserved by C.C. Cheung 2003.

6
Need for a source file
 If the JavaScript code is fairly short, you are
recommended to include the code in the
HTML document.
 To add clarity to an HTML document.
 To share JavaScript code across multiple
HTML documents.
 To help you hide your JavaScript code.
– Spent lot of time for JavaScript coding.
– Viewer can only see the location of the source
file but not the contents.

INE2720 – Web Application Software Development 13 All copyrights reserved by C.C. Cheung 2003.

Hide JavaScript from


incompatible browsers
<script language=
language=“JavaScript”
JavaScript”>
<!–
<!– begin hiding JavaScript
// single-
single-line comment,
comment, /* … */ multiple-
multiple-line comment
End hiding JavaScript -->
-->
</script>
<noscript>
noscript>
Your browser does not support JavaScript.
</noscript
</noscript>>

 Not all browsers support JavaScript.


 E.g. NN1, IE2, character-
character-based lynx.
INE2720 – Web Application Software Development 14 All copyrights reserved by C.C. Cheung 2003.

7
JavaScript confusion

JavaScript Java
Interpreted by the client-
client-side Compiled on the server before
computer executed on the client machine
Dynamic binding, object references Static binding, object references
are checked at runtime must exist at compile time
No need to declare data types Data types must be declared
Code is embedded in HTML Code is not integrated in HTML

Limited by the browser functionality Java applications are standalone


Can access browser objects Java has no access to browser
objects

INE2720 – Web Application Software Development 15 All copyrights reserved by C.C. Cheung 2003.

Using the alert() Method


<head>
<script language=
language=“JavaScript”
JavaScript”>
alert(“
alert(“An alert triggered by JavaScript”
JavaScript”);
</script>
</head>

 It is the easiest methods to use amongst


alert(), prompt() and confirm().
 You can use it to display textual information
to the user (simple and concise).
 The user can simply click “OK”
OK” to close it.
INE2720 – Web Application Software Development 16 All copyrights reserved by C.C. Cheung 2003.

8
Using the confirm() Method

<head>
<script language=
language=“JavaScript”
JavaScript”>
confirm(“
confirm(“Are you happy with the class?”
class?”);
</script>
</head>

 This box is used to give the user a choice


either OK or Cancel.
 It is very similar to the “alert()”
alert()” method.
 You can also put your message in the
method.
INE2720 – Web Application Software Development 17 All copyrights reserved by C.C. Cheung 2003.

Using the alert() Method


<head>
<script language=
language=“JavaScript”
JavaScript”>
prompt(“
prompt(“What is your student id number?”
number?”);
prompt(“
prompt(“What is your name?”
name?”,”No name”
name”);
</script>
</head>

 This is the only one that allows the user to


type in his own response to the specific
question.
 You can give a default value to avoid
displaying “undefined”
undefined”.
INE2720 – Web Application Software Development 18 All copyrights reserved by C.C. Cheung 2003.

9
Three methods
<script language="JavaScript">
alert("This is an Alert method");
confirm("Are you OK?");
prompt("What is your name?");
prompt("How old are you?","20");
</script>

INE2720 – Web Application Software Development 19 All copyrights reserved by C.C. Cheung 2003.

Variables
 JavaScript allows you to declare and use
variables to store values.
 How to assign a name to a variable?
– Include uppercase and lowercase letters
– Digits from 0 through 9
– The underscore _ and the dollar sign $
– No space and punctuation characters
– First character must be alphabetic letter or
underscore – 99Total?, 012345number?, …
– Case-
Case-sensitive
– No reserved words or keywords
INE2720 – Web Application Software Development 20 All copyrights reserved by C.C. Cheung 2003.

10
Which one is legal?
My_variable
Legal
$my_variable
1my_example
_my_variable
@my_variable
My_variable_example
++my_variable
%my_variable Illegal
#my_variable
~my_variable
myVariableExample
INE2720 – Web Application Software Development 21 All copyrights reserved by C.C. Cheung 2003.

Variable on-the-fly
<head>
<script language=
language=“JavaScript”
JavaScript”>
Variable declaration
var id;
id = prompt(“
prompt(“What is your student id number?”
number?”);
alert(id);
name = prompt(“
prompt(“What is your name?”
name?”,”No name”
name”);
alert(name);
</script>
</head>

 We should use “var”


var” because it is more
easy to keep track of the variables.
INE2720 – Web Application Software Development 22 All copyrights reserved by C.C. Cheung 2003.

11
Data Types
 JavaScript allows the same variable to contain
different types of data values.
 Primitive data types
– Number:
Number: integer & floating-
floating-point numbers
– Boolean:
Boolean: logical values “true”
true” or “false”
false”
– String:
String: a sequence of alphanumeric characters
 Composite data types (or Complex data types)
– Object:
Object: a named collection of data
– Array:
Array: a sequence of values
 Special data types
– Null:
Null: an initial value is assigned
– Undefined:
Undefined: the variable has been created by not yet
assigned a value
INE2720 – Web Application Software Development 23 All copyrights reserved by C.C. Cheung 2003.

Numeric Data Types

 It is an important part of any


programming language for doing
arithmetic calculations.
 JavaScript supports:
– Integers: A positive or negative number
with no decimal places.
 Ranged from –253 to 253
– Floating-
Floating-point numbers: usually written in
exponential notation.
 3.1415…
3.1415…, 2.0e11
INE2720 – Web Application Software Development 24 All copyrights reserved by C.C. Cheung 2003.

12
Integer and Floating-
point number example
<script language=
language=“JavaScript”
JavaScript”>
var integerVar = 100;
var floatingPointVar = 3.0e10;
// floating-
floating-point number 30000000000
document.write(integerVar);
document.write(integerVar);
document.write(floatingPointVar);
document.write(floatingPointVar);
</script>

 The integer 100 and the number


30,000,000,000 will be appeared in the
browser window.
INE2720 – Web Application Software Development 25 All copyrights reserved by C.C. Cheung 2003.

Boolean Values

 A Boolean value is a logical value of


either true or false. (yes/no, on/off)
 Often used in decision making and
data comparison.
 In JavaScript, you can use the words
“true”
true” and “false”
false” directly to indicate
Boolean values.
 Named by the 19th century
mathematician “George Boole”
Boole”.
INE2720 – Web Application Software Development 26 All copyrights reserved by C.C. Cheung 2003.

13
Boolean value example
<head>
<script language=
language=“JavaScript”
JavaScript”>
var result;
result = (true*10 + false*7);
alert(“
alert(“true*10 + false*7 = “, result);
</script>
</head>
 The expression is converted to
– (1*10 + 0*7) = 10
 They are automatically converted.
INE2720 – Web Application Software Development 27 All copyrights reserved by C.C. Cheung 2003.

Strings

 A string variable can store a sequence


of alphanumeric characters, spaces
and special characters.
 String can also be enclosed in single
quotation marks (‘(‘) or in double
quotation marks (“(“).
 What is the data type of “100”
100”?
– String but not number type
 Pay attention to the special characters.
INE2720 – Web Application Software Development 28 All copyrights reserved by C.C. Cheung 2003.

14
Strings example
<head>
<script language=
language=“JavaScript”
JavaScript”>
document.write(“
document.write(“This is a string.”
string.”);
document.write(“
document.write(“This string contains ‘quote’
quote’.”);
var myString = “My testing string”
string”;
alert(myString);
alert(myString);
</script>
</head>

 Unlike Java and C, JavaScript does not


have a single character (char) data
type.
INE2720 – Web Application Software Development 29 All copyrights reserved by C.C. Cheung 2003.

typeof operator
<head>
<script language=
language=“JavaScript”
JavaScript”>
var x = “hello”
hello”, y;
alert(“
alert(“Variable x value is “ + typeof(x));
typeof(x));
alert(“
alert(“Variable y value is “ + typeof(y));
typeof(y));
alert(“
alert(“Variable x value is “ + typeof(z));
typeof(z));
</script>
</head>

 It is an unary operator.
– Return either: Number, string, Boolean,
object, function, undefined, null
INE2720 – Web Application Software Development 30 All copyrights reserved by C.C. Cheung 2003.

15
What is an Object?
 An object is a thing, anything, just as things
in the real world.
– E.g. (cars, dogs, money, books, … )
 In the web browser, objects are the browser
window itself, forms, buttons, text boxes, …
 Methods are things that objects can do.
– Cars can move, dogs can bark.
– Window object can alert the user “alert()”
alert()”.
 All objects have properties.
– Cars have wheels, dogs have fur.
– Browser has a name and version number.
INE2720 – Web Application Software Development 31 All copyrights reserved by C.C. Cheung 2003.

Array

 An Array contains a set of data


represented by a single variable name.
 Arrays in JavaScript are represented
by the Array Object, we need to “new
Array()”
Array()” to construct this object.
 The first element of the array is
“Array[0]”
Array[0]” until the last one Array[i-
Array[i-1].
 E.g. myArray = new Array(5)
– We have myArray[0,1,2,3,4].
INE2720 – Web Application Software Development 32 All copyrights reserved by C.C. Cheung 2003.

16
Array Example
<script language=
language=“JavaScript”
JavaScript”>
Car = new Array(3);
Car[0] = “Ford”
Ford”;
Car[1] = “Toyota”
Toyota”;
Car[2] = “Honda”
Honda”;
document.write(Car[0] + “<br>
br>”);
document.write(Car[1] + “<br>
br>”);
document.write(Car[2] + “<br>
br>”);
</script>
 You can also declare arrays with variable length.
– arrayName = new Array();
– Length = 0, allows automatic extension of the length.
– Car[9] = “Ford”
Ford”; Car[99] = “Honda”
Honda”;
INE2720 – Web Application Software Development 33 All copyrights reserved by C.C. Cheung 2003.

Null & Undefined

 An “undefined”
undefined” value is returned when
you attempt to use a variable that has
not been defined or you have declared
but you forgot to provide with a value.
 Null refers to “nothing”
nothing”
 You can declare and define a variable
as “null”
null” if you want absolutely nothing
in it, but you just don’
don’t want it to be
“undefined”
undefined”.
INE2720 – Web Application Software Development 34 All copyrights reserved by C.C. Cheung 2003.

17
Null & Undefined example
<html>
<head>
<title> Null and Undefined example </title>
<script language=“
language=“JavaScript”
JavaScript”>
var test1, test2 = null;
alert(“
alert(“No value assigned to the variable”
variable” + test1);
alert(“
alert(“A null value was assigned”
assigned” + test2);
</script>
</head>
<body> … </body>
</html>

INE2720 – Web Application Software Development 35 All copyrights reserved by C.C. Cheung 2003.

JavaScript Special Characters

Character Meaning
\b Backspace
\f Form feed
\t Horizontal tab
\n New line
\r Carriage return
\\ Backslash
\’ Single quote
\” Double quote
INE2720 – Web Application Software Development 36 All copyrights reserved by C.C. Cheung 2003.

18
Break Time – 10 minutes

INE2720 – Web Application Software Development 37 All copyrights reserved by C.C. Cheung 2003.

Expressions

 It is a set of literals, variables,


operators that merge and evaluate to
a single value.
– Left_operand operator right_operand
 By using different operators, you can
create the following expressions.
– Arithmetic, logical
– String and conditional expressions.

INE2720 – Web Application Software Development 38 All copyrights reserved by C.C. Cheung 2003.

19
Operators

 Arithmetic operators
 Logical operators
 Comparison operators
 String operators
 Bit-
Bit-wise operators
 Assignment operators
 Conditional operators

INE2720 – Web Application Software Development 39 All copyrights reserved by C.C. Cheung 2003.

Arithmetic operators

 left_operand “operator”
operator” right_operand

Operator Name Description Example


+ Addition Adds the operands 3+5

- Subtraction Subtracts the right operand 5-3


from the left operand
* Multiplication Multiplies the operands 3*5
/ Division Divides the left operand by the 30 / 5
right operand
% Modulus Calculates the remainder 20 % 5
INE2720 – Web Application Software Development 40 All copyrights reserved by C.C. Cheung 2003.

20
Unary Arithmetic
Operators
 Binary operators take two operands.
 Unary type operators take only one
operand.
 Which one add value first, and then assign
value to the variable?
Name Example
Post Incrementing operator Counter++
Post Decrementing operator Counter--
Counter--
Pre Incrementing operator ++counter
Pre Decrementing operator --counter
--counter

INE2720 – Web Application Software Development 41 All copyrights reserved by C.C. Cheung 2003.

Logical operators
 Used to perform Boolean operations on
Boolean operands

Operator Name Description Example


&& Logical and Evaluate to “true”
true” when both 3>2 &&
operands are true 5<2
|| Logical or Evaluate to “true when either 3>1 || 2>5
operand is true
! Logical not Evaluate to “true”
true” when the 5 != 3
operand is false

INE2720 – Web Application Software Development 42 All copyrights reserved by C.C. Cheung 2003.

21
Comparison operators

 Used to compare two numerical values


Operator Name Description Example
== Equal Perform type conversion before checking the “5” == 5
equality
=== Strictly equal No type conversion before testing “5” === 5
!= Not equal “true”
true” when both operands are not equal 4 != 2
!== Strictly not equal No type conversion before testing nonequality 5 !== “5”
> Greater than “true”
true” if left operand is greater than right operand 2>5

< Less than “true”


true” if left operand is less than right operand 3<5

>= Greater than or “true”


true” if left operand is greater than or equal to the 5 >= 2
equal right operand
<= Less than or “true”
true” if left operand is less than or equal to the 5 <= 2
equal right operand
INE2720 – Web Application Software Development 43 All copyrights reserved by C.C. Cheung 2003.

Strict Equality Operators

<script language=“
language=“JavaScript”
JavaScript”>
var currentWord=
currentWord=“75”
75”;
var currentValue=75;
currentValue=75;
var outcome1=(currentWord
outcome1=(currentWord == currentValue);
currentValue);
var outcome2=(currentWord
outcome2=(currentWord === currentValue);
currentValue);
alert(“
alert(“outcome1: “ + outcome1 + “ : outcome2: “ + outcome2);
</script>

 Surprised that outcome1 is True!


 JavaScript tries very hard to resolve
numeric and string differences.
INE2720 – Web Application Software Development 44 All copyrights reserved by C.C. Cheung 2003.

22
String operator

 JavaScript only supports one string


operator for joining two strings.
Operator Name Description Return value
+ String Joins two strings “HelloWorld”
HelloWorld”
concatenation

<script language=“
language=“JavaScript”
JavaScript”>
var myString = “”;
“”;
myString = “Hello”
Hello” + “World”
World”;
alert(myString);
alert(myString);
</script>

INE2720 – Web Application Software Development 45 All copyrights reserved by C.C. Cheung 2003.

Bit Manipulation operators


 Perform operations on the bit representation
of a value, such as shift left or right.
Operator Name Description
& Bitwise AND Examines each bit position
| Bitwise OR If either bit of the operands is 1, the result will be 1
^ Bitwise XOR Set the result bit, only if either bit is 1, but not both
<< Bitwise left Shifts the bits of an expression to the left
shift
>> Bitwise signed Shifts the bits to the right, and maintains the sign
right shift
>>> Bitwise zero-
zero-fill Shifts the bits of an expression to right
right shift

INE2720 – Web Application Software Development 46 All copyrights reserved by C.C. Cheung 2003.

23
Assignment operators

 Used to assign values to variables


Operator Description Example
= Assigns the value of the right operand to the left operand A=2
+= Add the operands and assigns the result to the left A += 5
operand
-= Subtracts the operands and assigns the result to the left A -= 5
operand
*= Multiplies the operands and assigns the result to the left A *= 5
operand
/= Divides the left operands by the right operand and assigns A /= 5
the result to the left operand
%= Assigns the remainder to the left operand A %= 2

INE2720 – Web Application Software Development 47 All copyrights reserved by C.C. Cheung 2003.

The most common problem

<script language=“
language=“JavaScript”
JavaScript”>
if (alpha = beta) { … }
if (alpha == beta) { … }
</script>

 Don’
Don’t mix the comparison operator
and the assignment operator.
 double equal sign (==) and the equal
operator (=)

INE2720 – Web Application Software Development 48 All copyrights reserved by C.C. Cheung 2003.

24
Order of Precedence
Precedence Operator
1 Parentheses, function calls
2 , ~, -, ++, --,
--, new, void, delete
3 *, /, %
4 +, -
5 <<, >>, >>>
6 <, <=, >, >=
7 ==, !=, ===, !==
8 &
9 ^
10 |
11 &&
12 ||
13 ?:
14 =, +=, -=, *=, …
15 The comma
49
(,) operatorAll copyrights reserved by C.C. Cheung 2003.
INE2720 – Web Application Software Development

Precedence Example

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


Value = 3 / 1 – 1 - !false
Value = 3 / 1 – 1 - true
Value = 3 – 1 - true
Value = 3 – 2
Value = 1
INE2720 – Web Application Software Development 50 All copyrights reserved by C.C. Cheung 2003.

25
Scope of a Variable

 When you use a variable in a


JavaScript program that uses
functions.
 A global scope variable is one that is
declared outside a function and is
accessible in any part of your
program.
 A local variable is declared inside a
function and stops existing when the
function ends.
INE2720 – Web Application Software Development 51 All copyrights reserved by C.C. Cheung 2003.

Example of variable, data types


<html><head><title> Billing System of Web Shoppe </title></head><body>
</title></head><body>
<h1 align="center"> Billing System of Web Shoppe </h1>
<script language="JavaScript">
firstCustomer = new Array();
billDetails = new Array(firstCustomer
Array(firstCustomer););
var custName
custName,, custDob
custDob,, custAddress
custAddress,, custCity
custCity,, custPhone
custPhone;;
var custAmount
custAmount,, custAmountPaid
custAmountPaid,, custBalAmount
custBalAmount;;
custName=prompt("Enter
custName =prompt("Enter the first customer's name:", "");
custDob=prompt("Enter
custDob =prompt("Enter the first customer's date of birth:", "");
custAddress=prompt("Enter
custAddress =prompt("Enter the first customer's address:", "");
custPhone=prompt("Enter
custPhone =prompt("Enter the first customer's phone number:", "");
custAmount=prompt("Enter
custAmount =prompt("Enter the total bill amount of the first customer:", "");
"");
custAmountPaid=prompt("Enter
custAmountPaid =prompt("Enter the amount paid by the first customer:", "");
custBalAmount = custAmount - custAmountPaid
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 forfor first customer:" + "<BR>");
document.write("Name: " + billDetails[0][0] + "<BR>");
document.write("Date of Birth: " + billDetails[0][1] + "<BR>");
document.write("Address: " + billDetails[0][2] + "<BR>");
document.write("Phone: " + billDetails[0][3] + "<BR>");
(custBalAmount == 0) ? document.write("Amount Outstanding: " + custBalAmount):document.write("No amount due")
</script></body></html>
INE2720 – Web Application Software Development 52 All copyrights reserved by C.C. Cheung 2003.

26
Output of the code

INE2720 – Web Application Software Development 53 All copyrights reserved by C.C. Cheung 2003.

Conditional Statement

 “if” statement
 “if … else” statement

 “else if” statement

 “if/if … else” statement

 “switch” statement

INE2720 – Web Application Software Development 54 All copyrights reserved by C.C. Cheung 2003.

27
“if” statement

if (condition)
condition) { statements; }
 It is the main conditional statement in
JavaScript.
 The keyword “if”
if” always appears in
lowercase.
 The condition yields a logical true or false
value.
 The condition is true, statements are
executed.
INE2720 – Web Application Software Development 55 All copyrights reserved by C.C. Cheung 2003.

“if” statement example

<script language=“
language=“JavaScript”
JavaScript”>
var chr = “”;
“”;

if (chr
(chr == ‘A’ || chr == ‘O’) {
document.write(“
document.write(“Vowel variable”
variable”);
}
</script>

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

INE2720 – Web Application Software Development 56 All copyrights reserved by C.C. Cheung 2003.

28
“if … else” statement

if (condition)
condition) { statements; }
else { statements; }

 You can include an “else”


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

INE2720 – Web Application Software Development 57 All copyrights reserved by C.C. Cheung 2003.

Ternary Shortcut (concise)


<script language=“
language=“JavaScript”
JavaScript”>
If (3 > 2) {
alert(“
alert(“True”
True”);
} else {
alert(“
alert(“False”
False”);
}

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

 Substitute for a simple “if/else”


if/else” statement.
INE2720 – Web Application Software Development 58 All copyrights reserved by C.C. Cheung 2003.

29
“else if” statement

if (condition)
condition) { statement; }
else if (condition)
condition) { statement; }
else { statement; }

 Allows you to test for multiple


expression for one true value and
executes a particular block of code.

INE2720 – Web Application Software Development 59 All copyrights reserved by C.C. Cheung 2003.

“if/if…else” statement example


<script language=“
language=“JavaScript”
JavaScript”>
var chr;
chr;
chr = prompt(“
prompt(“Please enter a character : “,””);
””);
if (chr
(chr >= ‘A’){
if (chr
(chr <= ‘Z’)
alert(“
alert(“Uppercase”
Uppercase”);
else if (chr
(chr >= ‘a’){
alert(“
alert(“Lowercase”
Lowercase”);
}
}
</script>
INE2720 – Web Application Software Development 60 All copyrights reserved by C.C. Cheung 2003.

30
“switch” statement
switch (expression)
expression) {
case label1:
statements; break;
default:
statements;
}

 Allows you to merge several


evaluation tests of the same variable
into a single block of statements.
INE2720 – Web Application Software Development 61 All copyrights reserved by C.C. Cheung 2003.

“switch” statement example

<script language=“
language=“JavaScript”
JavaScript”>
var chr;
chr;
chr = prompt(“
prompt(“Pls enter a character in lowercase:”
lowercase:”,””);
””);
switch(chr){
switch(chr){
case ‘a’ :
alert(“
alert(“Vowel a”
a”); break;
case ‘e’ :
alert(“
alert(“Vowel e”
e”); break;
default :
alert(“
alert(“Not a vowel”
vowel”);
}
</script>

INE2720 – Web Application Software Development 62 All copyrights reserved by C.C. Cheung 2003.

31
Looping Statement

 “for”
for” Loops
 “for/in”
for/in” Loops
 “while”
while” Loops
 “do … while”
while” Loops
 “break”
break” statement
 “continue”
continue” statement

INE2720 – Web Application Software Development 63 All copyrights reserved by C.C. Cheung 2003.

“for” statement
for (initial_expression; test_exp; change_exp)
change_exp)
{ statements; }

 One of the most used and familiar loops is


the for loop.
 It iterates through a sequence of
statements for a number of times controlled
by a condition.
 The change_exp determines how much has
been added or subtracted from the counter
variable.
INE2720 – Web Application Software Development 64 All copyrights reserved by C.C. Cheung 2003.

32
“for” statement example
<script language=“
language=“JavaScript”
JavaScript”>
var counter;
for (counter = 1;
1; counter <= 10; counter++)
counter++)
{
document.write(counter*counter + “ “);
}
</script>

 Display the square of numbers


 Output: 1 4 9 16 25 36 49 64 81 100
INE2720 – Web Application Software Development 65 All copyrights reserved by C.C. Cheung 2003.

“for/in” statement
for (counter_variable in object)
{ statements; }

 When the for/in statement is used, the


counter and termination are determined by
the length of the object.
 The statement begins with 0 as the initial
value of the counter variable, terminates
with all the properties of the objects have
been exhausted.
– E.g. array  no more elements found
INE2720 – Web Application Software Development 66 All copyrights reserved by C.C. Cheung 2003.

33
“for/in” statement example

<script language=“
language=“JavaScript”
JavaScript”>
var book; (What is the difference if “var book=“”
book=“”;)
;)
var booklist = new Array(“
Array(“Chinese”
Chinese”, “English”
English”, “Jap”
Jap”);
for (var
(var counter in booklist)
booklist) {
book += booklist[counter] + “ “;
}
alert(book);
</script>

INE2720 – Web Application Software Development 67 All copyrights reserved by C.C. Cheung 2003.

“while” statement
initial value declaration;
while (condition)
condition) {
statements;
increment/decrement statement;
}

 The while loop begins with a termination condition


and keeps looping until the termination condition is
met.
 The counter variable is managed by the context of
the statements inside the curly braces.
INE2720 – Web Application Software Development 68 All copyrights reserved by C.C. Cheung 2003.

34
“While” statement example
<html>
<head>
<title>While loop example</title>
<script language=“
language=“JavaScript”
JavaScript”>
var counter = 100;
var numberlist = “”;
“”;
while (counter > 0)
0) {
numberlist += “Number “ + counter + “<br>
br>”;
counter -= 10;
}
document.write(numberlist);
document.write(numberlist);
</script> <body> … </body>
</html>
INE2720 – Web Application Software Development 69 All copyrights reserved by C.C. Cheung 2003.

“do … while” statement


do {
statements;
counter increment/decrement;
} while (termination condition)
condition)

 The do/while loop always executes


statements in the loop in the first
iteration of the loop.
 The termination condition is placed at
the bottom of the loop.
INE2720 – Web Application Software Development 70 All copyrights reserved by C.C. Cheung 2003.

35
Example of Flow Control

INE2720 – Web Application Software Development 71 All copyrights reserved by C.C. Cheung 2003.

References

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

 The End.
 Thank you for patience!

INE2720 – Web Application Software Development 72 All copyrights reserved by C.C. Cheung 2003.

36

You might also like