Introduction to Java Script
JavaScript: Control & Looping Statements
Control Structures
Sequential execution
Statements execute in the order they are written
Transfer of control
Next statement to execute may not be the next one in sequence
Three control structures
Sequence structure
Selection structure
if
ifelse
switch
Repetition structure
while
dowhile
for
forin
Control Structures
Flowchart
Graphical representation of algorithm or portion of algorithm
Flowlines
Rectangle symbol
A complete algorithm
Small circle symbol
Indicate any type of action
Oval symbol
Indicate the order the actions of the algorithm execute
A portion of algorithm
Diamond symbol
Indicates a decision is to be made
Control Structures
add grade to total
total = total + grade;
add 1 to counter
counter = counter + 1;
Flowcharting JavaScripts sequence structure.
JavaScript Keywords
JavaScript
Keywords
break
case
catch
delete
do
else
function
if
in
return
switch
this
typeof
var
void
Keywords that
are reserved but
not currently
used by
JavaScript
abstract
boolean
byte
const
debugger
double
extends
final
float
import
int
interface
package
private
protected
static
super
synchronized
volatile
Fig. 8.2 JavaScript keywords.
continue
finally
instanceof
throw
while
default
for
new
try
with
char
enum
goto
long
public
throws
class
export
implements
native
short
transient
if Selection Statement
Single-entry/single-exit structure
Indicate action only when the condition evaluates to
true
if Selection Statement
grade >= 60
true
print Passed
false
Flowcharting the single-selection if statement.
ifelse Selection Statement
Indicate different actions to be perform when
condition is true or false
Conditional operator (?:)
JavaScripts only ternary operator
Three operands
Forms a conditional expression
ifelse Selection Statement
false
print Failed
grade >= 60
true
print Passed
Flowcharting the double-selection ifelse statement.
while Repetition Statement
Repetition structure (loop)
Repeat action while some condition remains true
while Repetition Statement
product <= 1000
true
false
Flowcharting the while repetition statement.
product =
2 * product
Formulating Algorithms:
Case Study 1 (Counter-Controlled Repetition)
Counter-controlled repetition
Counter
Control the number of times a set of statements executes
Definite repetition
average.html
(1 of 3)
24
// Processing Phase
25
while ( gradeCounter <= 10 ) {
// loop 10 times
26
27
// prompt for input and read grade from user
28
grade = window.prompt( "Enter integer grade:", "0" );
average.html
(2 of 3)
29
30
// convert grade from a string to an integer
31
gradeValue = parseInt( grade );
32
33
// add gradeValue to total
34
total = total + gradeValue;
35
36
// add 1 to gradeCounter
37
gradeCounter = gradeCounter + 1;
38
39
40
// Termination Phase
41
average = total / 10;
// calculate the average
42
43
// display average of exam grades
44
document.writeln(
45
"<h1>Class average is " + average + "</h1>" );
46
// -->
47
</script>
48
49
</head>
50
<body>
51
52
<p>Click Refresh (or Reload) to run the script again<p>
</body>
53 </html>
Formulating Algorithms with Top-Down, Stepwise
Refinement: Case Study 2 (User-Controlled Repetition)
Indefinite repetition
Sentinel (User Controlled) value
average2.html
(1 of 3)
25
// Processing phase
26
// prompt for input and read grade from user
27
grade = window.prompt(
28
"Enter Integer Grade, -1 to Quit:", "0" );
average2.html
(2 of 3)
29
30
// convert grade from a string to an integer
31
gradeValue = parseInt( grade );
32
33
while ( gradeValue != -1 ) {
34
// add gradeValue to total
35
total = total + gradeValue;
36
37
// add 1 to gradeCounter
38
gradeCounter = gradeCounter + 1;
39
40
// prompt for input and read grade from user
41
grade = window.prompt(
42
"Enter Integer Grade, -1 to Quit:", "0" );
43
44
// convert grade from a string to an integer
45
gradeValue = parseInt( grade );
46
47
48
// Termination phase
49
if ( gradeCounter != 0 ) {
50
average = total / gradeCounter;
51
average2.html
52
// display average of exam grades
(35354 of 3) document.writeln(
"<h1>Class average is " + average + "</h1>" );
55
56
else
57
document.writeln( "<p>No grades were entered</p>" );
58
// -->
59
</script>
60
</head>
61
62
63
64
<body>
<p>Click Refresh (or Reload) to run the script again</p>
</body>
65 </html>
Formulating Algorithms with Top-Down, Stepwise
Refinement: Case Study 3 (Nested Control Structures)
Consider problem
Make observations
Top-down, stepwise refinement
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
analysis.html
(1 of 2)
5
<!-- Fig. 8.11: analysis.html -->
<!-- Analyzing Exam Results
-->
7
8
9
10
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Analysis of Examination Results</title>
11
12
<script type = "text/javascript">
13
<!--
14
// initializing variables in declarations
15
var passes = 0,
// number of passes
16
failures = 0,
// number of failures
17
student = 1,
// student counter
18
result;
// one exam result
19
20
// process 10 students; counter-controlled loop
21
while ( student <= 10 ) {
22
23
24
result = window.prompt(
"Enter result (1=pass,2=fail)", "0" );
25
if ( result == "1" )
26
passes = passes + 1;
27
else
28
analysis.html
(2 of 2)
failures = failures + 1;
29
30
student = student + 1;
31
32
33
// termination phase
34
document.writeln( "<h1>Examination Results</h1>" );
35
document.writeln(
36
"Passed: " + passes + "<br />Failed: " + failures );
37
38
if ( passes > 8 )
39
document.writeln( "<br />Raise Tuition" );
40
// -->
41
</script>
42
43
</head>
44
<body>
45
46
<p>Click Refresh (or Reload) to run the script again</p>
</body>
47 </html>
Assignment Operators
Compound assignment operators
Abbreviate assignment expressions
Assignment Operators
Increment and Decrement Operators
Preincrement or predecrement operator
Increment of decrement operator placed before a variable
Postincrement or postdecrement operator
Increment of decrement operator placed after a variable
Increment and Decrement Operators
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5
<!-- Fig. 8.14: increment.html
<!-- Preincrementing and Postincrementing -->
increment.html
(1 of 2)
-->
7
8
9
10
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Preincrementing and Postincrementing</title>
11
12
<script type = "text/javascript">
13
<!--
14
var c;
15
16
c = 5;
17
document.writeln( "<h3>Postincrementing</h3>" );
18
document.writeln( c );
19
// print 5 then increment
20
document.writeln( "<br />" + c++ );
21
document.writeln( "<br />" + c );
// print 5
// print 6
22
23
c = 5;
24
document.writeln( "<h3>Preincrementing</h3>" );
25
document.writeln( c );
// print 5
26
// increment then print 6
27
document.writeln( "<br />" + ++c );
28
document.writeln( "<br />" + c );
29
// -->
30
</script>
31
32
</head><body></body>
33 </html>
// print 6
Increment and Decrement Operators
Essentials of Counter-Controlled Repetition
Counter-controlled repetition
Name of a control
Initial value
Increment or decrement
Final value
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
WhileCounter.html
(1 of 2)
5
<!-- Fig. 9.1: WhileCounter.html
<!-- Counter-Controlled Repetition -->
-->
7
8
9
10
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Counter-Controlled Repetition</title>
11
12
<script type = "text/javascript">
13
<!--
14
var counter = 1;
// initialization
while ( counter <= 7 ) {
// repetition condition
15
16
17
document.writeln( "<p style = \"font-size: " +
18
counter + "ex\">XHTML font size " + counter +
19
"ex</p>" );
20
++counter;
21
22
// -->
23
</script>
24
// increment
25
</head><body></body>
26 </html>
WhileCounter.html
(2 of 2)
for Repetition Statement
for
repetition statement
Handles all the details of counter-controlled repetition
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
ForCounter.html
(1 of 1)
5
<!-- Fig. 9.2: ForCounter.html
<!-- Counter-Controlled Repetition with for statement -->
-->
7
8
9
10
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Counter-Controlled Repetition</title>
11
12
<script type = "text/javascript">
13
<!--
14
// Initialization, repetition condition and
15
// incrementing are all included in the for
16
// statement header.
17
for ( var counter = 1; counter <= 7; ++counter )
18
document.writeln( "<p style = \"font-size: " +
19
counter + "ex\">XHTML font size " + counter +
20
"ex</p>" );
21
// -->
22
</script>
23
24
</head><body></body>
25 </html>
for Repetition Statement
for keyword
Control variable name
Final value of control variable
for which the condition is true
for ( var counter = 1; counter <= 7; ++counter )
Initial value of control variable
Increment of control variable
Loop-continuation condition
for Repetition Statement
Establish
initial value
of control
variable.
var counter = 1
counter <= 7
false
Determine
if final value
of control
variable
has been
reached.
Fig. 9.4
true
document.writeln(
"<p style=\"font-size: "
+ counter +
"ex\">XHTML font size " +
counter + "ex</p>" );
Body of loop
(this may be many
statements)
for repetition structure flowchart.
++counter
Increment
the control
variable.
Examples Using the for Statement
Summation with for
Compound interest calculation with for loop
Math object
Method pow
Method round
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
Sum.html
(1 of 1)
5
<!-- Fig. 9.5: Sum.html
<!-- Using the for repetition statement -->
-->
7
8
9
10
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Sum the Even Integers from 2 to 100</title>
11
12
<script type = "text/javascript">
13
<!--
14
var sum = 0;
15
16
for ( var number = 2; number <= 100; number += 2 )
17
sum += number;
18
19
document.writeln( "The sum of the even integers " +
20
"from 2 to 100 is " + sum );
21
// -->
22
</script>
23
24
</head><body></body>
25 </html>
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
Interest.html
(1 of 2)
5
<!-- Fig. 9.6: Interest.html
<!-- Using the for repetition statement -->
-->
7
8
9
10
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Calculating Compound Interest</title>
11
12
<script type = "text/javascript">
13
<!--
14
var amount, principal = 1000.0, rate = .05;
15
16
17
18
19
20
21
22
23
24
25
document.writeln(
"<table border = \"1\" width = \"100%\">" );
document.writeln(
"<caption>Calculating Compound Interest</caption>" );
document.writeln(
"<thead><tr><th align = \"left\">Year</th>" );
document.writeln(
"<th align = \"left\">Amount on deposit</th>" );
document.writeln( "</tr></thead>" );
26
for ( var year = 1; year <= 10; ++year ) {
27
amount = principal * Math.pow( 1.0 + rate, year );
28
document.writeln( "<tbody><tr><td>" + year +
29
"</td><td>" + Math.round( amount * 100 ) / 100 +
30
"</td></tr>" );
Interest.html
(2 of 2)
31
32
33
document.writeln( "</tbody></table>" );
34
// -->
35
</script>
36
37
</head><body></body>
38 </html>
switch Multiple-Selection Statement
Controlling expression
Case labels
Default case
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
SwitchTest.html
(1 of 3)
5
<!-- Fig. 9.7: SwitchTest.html
<!-- Using the switch statement -->
-->
7
8
9
10
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Switching between XHTML List Formats</title>
11
12
<script type = "text/javascript">
13
<!--
14
var choice,
// users choice
15
startTag,
// starting list item tag
16
endTag,
// ending list item tag
17
validInput = true,
// indicates if input is valid
18
listType;
// list type as a string
19
20
21
22
choice = window.prompt( "Select a list style:\n" +
"1 (bullet), 2 (numbered), 3 (lettered)", "1" );
23
switch ( choice ) {
24
case "1":
25
startTag = "<ul>";
26
endTag = "</ul>";
SwitchTest.html
(2 of 3)
27
listType = "<h1>Bullet List</h1>";
28
break;
29
case "2":
30
startTag = "<ol>";
31
endTag = "</ol>";
32
listType = "<h1>Ordered List: Numbered</h1>";
33
break;
34
case "3":
35
startTag = "<ol type = \"A\">";
36
endTag = "</ol>";
37
listType = "<h1>Ordered List: Lettered</h1>";
38
break;
39
default:
40
41
validInput = false;
}
42
43
44
if ( validInput == true ) {
document.writeln( listType + startTag );
45
46
47
for ( var i = 1; i <= 3; ++i )
document.writeln( "<li>List item " + i + "</li>" );
48
49
document.writeln( endTag );
50
51
else
SwitchTest.html
(3 of 3)
52
document.writeln( "Invalid choice: " + choice );
53
// -->
54
</script>
55
56
</head>
57
<body>
58
59
<p>Click Refresh (or Reload) to run the script again</p>
</body>
60 </html>
switch Multiple-Selection Statement
case a
true
case a action(s)
break
case b action(s)
break
case z action(s)
break
false
case b
true
false
.
.
.
case z
false
default action(s)
true
dowhile Repetition Statement
Similar to the while statement
Tests the loop continuation condition after the loop
body executes
Loop body always executes at least once
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
DoWhileTest.html
(1 of 2)
5
<!-- Fig. 9.9: DoWhileTest.html
<!-- Using the do...while statement -->
-->
7
8
9
10
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Using the do...while Repetition Statement</title>
11
12
<script type = "text/javascript">
13
<!--
14
var counter = 1;
15
16
do {
17
document.writeln( "<h" + counter + ">This is " +
18
"an h" + counter + " level head" + "</h" +
19
counter + ">" );
20
21
++counter;
22
} while ( counter <= 6 );
23
// -->
24
</script>
25
26
</head><body></body>
27 </html>
dowhile Repetition Structure
action(s)
condition
false
true
break and continue Statements
break
Immediate exit from the structure
Used to escape early from a loop
Skip the remainder of a switch statement
continue
Skips the remaining statements in the body of the structure
Proceeds with the next iteration of the loop
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
BreakTest.html
(1 of 2)
5
<!-- Fig. 9.11: BreakTest.html
-->
<!-- Using the break statement
-->
7
8
9
10
11
12
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>
Using the break Statement in a for Structure
</title>
13
14
<script type = "text/javascript">
15
<!--
16
for ( var count = 1; count <= 10; ++count ) {
17
if ( count == 5 )
18
break;
// break loop only if count == 5
19
20
21
22
document.writeln( "Count is: " + count + "<br />" );
}
23
document.writeln(
24
"Broke out of loop at count = " + count );
25
// -->
26
</script>
27
28
</head><body></body>
29 </html>
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
ContinueTest.html
(1 of 2)
5
<!-- Fig. 9.12: ContinueTest.html
-->
<!-- Using the break statement
-->
7
8
9
10
11
12
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>
Using the continue Statement in a for Structure
</title>
13
14
<script type = "text/javascript">
15
<!--
16
for ( var count = 1; count <= 10; ++count ) {
17
if ( count == 5 )
18
continue;
19
// skip remaining code in loop
// only if count == 5
20
21
22
23
document.writeln( "Count is: " + count + "<br />" );
}
24
document.writeln( "Used continue to skip printing 5" );
25
// -->
26
</script>
27
28
</head><body></body>
29 </html>
Labeled break and continue Statements
Labeled break statement
Break out of a nested set of structures
Immediate exit from that structure and enclosing repetition
structures
Execution resumes with first statement after enclosing labeled
statement
Labeled continue statement
Skips the remaining statements in structures body and enclosing
repetition structures
Proceeds with next iteration of enclosing labeled repetition structure
Loop-continuation test evaluates immediately after the continue
statement executes
BreakLabelTest.html
(1 of 2)
BreakLabelTest.html
(2 of 2)
Logical Operators
More logical operators
Logical AND ( && )
Logical OR ( || )
Logical NOT ( ! )
Logical Operators
Logical Operators
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5
<!-- Fig. 9.18: LogicalOperators.html
LogicalOperators.html
6
-->
<!-- Demonstrating Logical Operators
(1 of 2)
-->
7
8
9
10
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Demonstrating the Logical Operators</title>
11
12
<script type = "text/javascript">
13
<!--
14
document.writeln(
15
"<table border = \"1\" width = \"100%\">" );
16
17
document.writeln(
18
"<caption>Demonstrating Logical " +
19
"Operators</caption" );
20
21
document.writeln(
22
"<tr><td width = \"25%\">Logical AND (&&)</td>" +
23
"<td>false && false: " + ( false && false ) +
24
"<br />false && true: " + ( false && true ) +
25
"<br />true && false: " + ( true && false ) +
26
"<br />true && true: " + ( true && true ) +
27
"</td>" );
28
29
document.writeln(
30
"<tr><td width = \"25%\">Logical OR (||)</td>" +
31
"<td>false || false: " + ( false || false ) +
32
"<br />false || true: " + ( false || true ) +
33
"<br />true || false: " + ( true || false ) +
34
"<br />true || true: " + ( true || true ) +
35
"</td>" );
LogicalOperators.html
(2 of 2)
36
37
document.writeln(
38
"<tr><td width = \"25%\">Logical NOT (!)</td>" +
39
"<td>!false: " + ( !false ) +
40
"<br />!true: " + ( !true ) + "</td>" );
41
42
document.writeln( "</table>" );
43
// -->
44
</script>
45
46
</head><body></body>
47 </html>
Logical Operators