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
if…else
switch

Repetition structure



while
do…while
for
for…in

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. Flowcharting JavaScript’s sequence structure. add 1 to counter counter = counter + 1. .

2 JavaScript keywords.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. continue finally instanceof throw while   default for new try with char enum goto long public throws class export implements native short transient . 8.

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. .

if…else Selection Statement Indicate different actions to be perform when condition is true or false Conditional operator (?:)  JavaScript’s only ternary operator   Three operands Forms a conditional expression .

.if…else Selection Statement false print “Failed” grade >= 60 true print “Passed” Flowcharting the double-selection if…else 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 .

html (1 of 3) .average.

// calculate the average 42 43 // display average of exam grades 44 document. 35 36 // add 1 to gradeCounter 37 gradeCounter = gradeCounter + 1. 38 } 39 40 // Termination Phase 41 average = total / 10. 32 33 // add gradeValue to total 34 total = total + gradeValue.prompt( "Enter integer grade:".24 // Processing Phase 25 while ( gradeCounter <= 10 ) { // loop 10 times 26 27 // prompt for input and read grade from user 28 grade = window.writeln( 45 "<h1>Class average is " + average + "</h1>" ).html (2 of 3) 29 30 // convert grade from a string to an integer 31 gradeValue = parseInt( grade ). average. 46 // --> 47 </script> . "0" ).

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 .

html (1 of 3) .average2.

46 47 } . "0" ).html (2 of 3) 29 30 // convert grade from a string to an integer 31 gradeValue = parseInt( grade ).prompt( 42 "Enter Integer Grade. -1 to Quit:". average2. -1 to Quit:".25 // Processing phase 26 // prompt for input and read grade from user 27 grade = window. 43 44 // convert grade from a string to an integer 45 gradeValue = parseInt( grade ). "0" ). 36 37 // add 1 to gradeCounter 38 gradeCounter = gradeCounter + 1. 32 33 while ( gradeValue != -1 ) { 34 // add gradeValue to total 35 total = total + gradeValue. 39 40 // prompt for input and read grade from user 41 grade = window.prompt( 28 "Enter Integer Grade.

writeln( "<p>No grades were entered</p>" ).48 // Termination phase 49 if ( gradeCounter != 0 ) { 50 average = total / gradeCounter. 55 } 56 else 57 document. 58 // --> 59 </script> 60 </head> 61 62 63 64 <body> <p>Click Refresh (or Reload) to run the script again</p> </body> 65 </html> .html 52 // display average of exam grades (35354 of 3) document. 51 average2.writeln( "<h1>Class average is " + average + "</h1>" ).

.

stepwise refinement .Formulating Algorithms with Top-Down. Stepwise Refinement: Case Study 3 (Nested Control Structures) Consider problem Make observations Top-down.

8.html (1 of 2) 5 <!-. // number of passes 16 failures = 0. "0" ). // student counter 18 result. // one exam result 19 20 // process 10 students.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.2=fail)".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.org/TR/xhtml1/DTD/xhtml1-strict.html --> 6 <!-.Analyzing Exam Results --> 7 8 9 10 <html xmlns = "http://www.w3.Fig.1 <?xml version = "1. .11: analysis. // number of failures 17 student = 1.0 Strict//EN" 3 "http://www.w3. counter-controlled loop 21 while ( student <= 10 ) { 22 23 24 result = window.dtd"> 4 analysis.prompt( "Enter result (1=pass.

37 38 if ( passes > 8 ) 39 document. 35 document. 27 else 28 analysis. 31 } 32 33 // termination phase 34 document.html (2 of 2) failures = failures + 1. 40 // --> 41 </script> 42 43 </head> 44 <body> 45 46 <p>Click Refresh (or Reload) to run the script again</p> </body> 47 </html> .writeln( "<br />Raise Tuition" ).writeln( 36 "Passed: " + passes + "<br />Failed: " + failures ).25 if ( result == "1" ) 26 passes = passes + 1.writeln( "<h1>Examination Results</h1>" ). 29 30 student = student + 1.

.

.

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 .

dtd"> 4 5 <!-.w3.0 Strict//EN" 3 "http://www. 24 document.org/1999/xhtml"> <head> <title>Preincrementing and Postincrementing</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 var c. // print 5 .html (1 of 2) --> 7 8 9 10 <html xmlns = "http://www.writeln( "<h3>Postincrementing</h3>" ).1 <?xml version = "1. 15 16 c = 5.writeln( c ). // print 5 // print 6 22 23 c = 5.w3.Preincrementing and Postincrementing --> increment.writeln( c ).html 6 <!-.Fig. 25 document. 19 // print 5 then increment 20 document. 8.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.writeln( "<br />" + c ). 17 document.14: increment. 21 document.writeln( "<br />" + c++ ).org/TR/xhtml1/DTD/xhtml1-strict. 18 document.writeln( "<h3>Preincrementing</h3>" ).

writeln( "<br />" + c ).26 // increment then print 6 27 document. 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 .

dtd"> 4 WhileCounter.html 6 <!-.Counter-Controlled Repetition --> --> 7 8 9 10 <html xmlns = "http://www.w3. 20 ++counter.org/TR/xhtml1/DTD/xhtml1-strict.Fig. 9.w3.1: WhileCounter.1 <?xml version = "1. // initialization while ( counter <= 7 ) { // repetition condition 15 16 17 document. 21 } 22 // --> 23 </script> 24 // increment .writeln( "<p style = ###BOT_TEXT###quot;font-size: " + 18 counter + "ex###BOT_TEXT###quot;>XHTML font size " + counter + 19 "ex</p>" ).0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.org/1999/xhtml"> <head> <title>Counter-Controlled Repetition</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 var counter = 1.0 Strict//EN" 3 "http://www.html (1 of 2) 5 <!-.

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 .

repetition condition and 15 // incrementing are all included in the for 16 // statement header.1 <?xml version = "1.org/1999/xhtml"> <head> <title>Counter-Controlled Repetition</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 // Initialization.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1. 9.0 Strict//EN" 3 "http://www. ++counter ) 18 document.dtd"> 4 ForCounter.w3. counter <= 7.org/TR/xhtml1/DTD/xhtml1-strict.Fig.writeln( "<p style = ###BOT_TEXT###quot;font-size: " + 19 counter + "ex###BOT_TEXT###quot;>XHTML font size " + counter + 20 "ex</p>" ).Counter-Controlled Repetition with for statement --> --> 7 8 9 10 <html xmlns = "http://www.w3. 21 // --> 22 </script> 23 24 </head><body></body> 25 </html> .html (1 of 1) 5 <!-. 17 for ( var counter = 1.html 6 <!-.2: ForCounter.

.

for Repetition Statement for keyword Control variable name Final value of control variable for which the condition is true for ( var counter = 1. ++counter ) Initial value of control variable Increment of control variable Loop-continuation condition . counter <= 7.

for Repetition Statement Establish initial value of control variable. ++counter Increment the control variable. Fig. Body of loop (this may be many statements) for repetition structure flowchart.4 true document.writeln( "<p style=###BOT_TEXT###quot;font-size: " + counter + "ex###BOT_TEXT###quot;>XHTML font size " + counter + "ex</p>" ). 9. . var counter = 1 counter <= 7 false Determine if final value of control variable has been reached.

Examples Using the for Statement Summation with for Compound interest calculation with for loop  Math object  Method pow  Method round .

15 16 for ( var number = 2.5: Sum.w3.writeln( "The sum of the even integers " + 20 "from 2 to 100 is " + sum ).Fig.dtd"> 4 Sum.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.Using the for repetition statement --> --> 7 8 9 10 <html xmlns = "http://www.w3. number <= 100. 18 19 document.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 "http://www.html (1 of 1) 5 <!-.html 6 <!-. 21 // --> 22 </script> 23 24 </head><body></body> 25 </html> . 9. number += 2 ) 17 sum += number.1 <?xml version = "1.org/TR/xhtml1/DTD/xhtml1-strict.

.

w3.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1. document.6: Interest.Using the for repetition statement --> --> 7 8 9 10 <html xmlns = "http://www.writeln( "<table border = ###BOT_TEXT###quot;1###BOT_TEXT###quot; width = ###BOT_TEXT###quot;100%###BOT_TEXT###quot;>" ).w3.html 6 <!-. 9.writeln( "<thead><tr><th align = ###BOT_TEXT###quot;left###BOT_TEXT###quot;>Year</th>" ).writeln( "<th align = ###BOT_TEXT###quot;left###BOT_TEXT###quot;>Amount on deposit</th>" ). document. rate = .org/1999/xhtml"> <head> <title>Calculating Compound Interest</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 var amount.dtd"> 4 Interest.org/TR/xhtml1/DTD/xhtml1-strict. principal = 1000. document.Fig.writeln( "<caption>Calculating Compound Interest</caption>" ). 15 16 17 18 19 20 21 22 23 24 25 document.writeln( "</tr></thead>" ).0 Strict//EN" 3 "http://www.05. .1 <?xml version = "1. document.0.html (1 of 2) 5 <!-.

26 for ( var year = 1.0 + rate. Interest.round( amount * 100 ) / 100 + 30 "</td></tr>" ).pow( 1. year <= 10.writeln( "<tbody><tr><td>" + year + 29 "</td><td>" + Math.html (2 of 2) 31 } 32 33 document. ++year ) { 27 amount = principal * Math. 34 // --> 35 </script> 36 37 </head><body></body> 38 </html> .writeln( "</tbody></table>" ). year ). 28 document.

switch Multiple-Selection Statement Controlling expression Case labels Default case .

2 (numbered). // list type as a string 19 20 21 22 choice = window. // starting list item tag 16 endTag.Fig.Using the switch statement --> --> 7 8 9 10 <html xmlns = "http://www.org/TR/xhtml1/DTD/xhtml1-strict.html (1 of 3) 5 <!-.0 Strict//EN" 3 "http://www.1 <?xml version = "1. // user’s choice 15 startTag.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.html 6 <!-.w3. . // ending list item tag 17 validInput = true.org/1999/xhtml"> <head> <title>Switching between XHTML List Formats</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 var choice.dtd"> 4 SwitchTest. // indicates if input is valid 18 listType.w3. "1" ).prompt( "Select a list style:\n" + "1 (bullet).7: SwitchTest. 3 (lettered)". 9.

34 case "3": 35 startTag = "<ol type = ###BOT_TEXT###quot;A###BOT_TEXT###quot;>". 45 46 47 for ( var i = 1. . 29 case "2": 30 startTag = "<ol>".23 switch ( choice ) { 24 case "1": 25 startTag = "<ul>".html (2 of 3) 27 listType = "<h1>Bullet List</h1>". 31 endTag = "</ol>". 28 break. 32 listType = "<h1>Ordered List: Numbered</h1>". ++i ) document. 37 listType = "<h1>Ordered List: Lettered</h1>". i <= 3. 38 break. } 42 43 44 if ( validInput == true ) { document. 33 break.writeln( listType + startTag ). 26 endTag = "</ul>". SwitchTest. 39 default: 40 41 validInput = false.writeln( "<li>List item " + i + "</li>" ). 36 endTag = "</ol>".

html (3 of 3) 52 document. 50 } 51 else SwitchTest.writeln( "Invalid choice: " + choice ).48 49 document.writeln( endTag ). 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 .

do…while Repetition Statement Similar to the while statement Tests the loop continuation condition after the loop body executes Loop body always executes at least once .

.while statement --> --> 7 8 9 10 <html xmlns = "http://www.Using the do. 9.html 6 <!-..0 Strict//EN" 3 "http://www.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.html (1 of 2) 5 <!-.dtd"> 4 DoWhileTest.w3.org/TR/xhtml1/DTD/xhtml1-strict. 23 // --> 24 </script> .while Repetition Statement</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 var counter = 1.1 <?xml version = "1. 22 } while ( counter <= 6 ).org/1999/xhtml"> <head> <title>Using the do. 15 16 do { 17 document.. 20 21 ++counter.9: DoWhileTest.writeln( "<h" + counter + ">This is " + 18 "an h" + counter + " level head" + "</h" + 19 counter + ">" ).Fig.w3..

25 26 </head><body></body> 27 </html> .

do…while 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 .

9. } .writeln( "Count is: " + count + "<br />" ).org/TR/xhtml1/DTD/xhtml1-strict.0 Strict//EN" 3 "http://www.1 <?xml version = "1. ++count ) { 17 if ( count == 5 ) 18 break.w3.Using the break statement --> 7 8 9 10 11 12 <html xmlns = "http://www.dtd"> 4 BreakTest. count <= 10.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.html (1 of 2) 5 <!-.html --> 6 <!-.w3. // break loop only if count == 5 19 20 21 22 document.Fig.11: BreakTest.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.

25 // --> 26 </script> 27 28 </head><body></body> 29 </html> .23 document.writeln( 24 "Broke out of loop at count = " + count ).

html (1 of 2) 5 <!-.w3. 19 // skip remaining code in loop // only if count == 5 20 21 22 23 document.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.dtd"> 4 ContinueTest.w3. } . count <= 10.writeln( "Count is: " + count + "<br />" ). ++count ) { 17 if ( count == 5 ) 18 continue.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.html --> 6 <!-.Fig.0 Strict//EN" 3 "http://www. 9.1 <?xml version = "1.12: ContinueTest.org/TR/xhtml1/DTD/xhtml1-strict.Using the break statement --> 7 8 9 10 11 12 <html xmlns = "http://www.

writeln( "Used continue to skip printing 5" ).24 document. 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 structure’s body and enclosing repetition structures Proceeds with next iteration of enclosing labeled repetition structure Loop-continuation test evaluates immediately after the continue statement executes .

html (1 of 2) .BreakLabelTest.

BreakLabelTest.html (2 of 2) .

.

.

Logical Operators More logical operators    Logical AND ( && ) Logical OR ( || ) Logical NOT ( ! ) .

Logical Operators .

Logical Operators .

writeln( 22 "<tr><td width = ###BOT_TEXT###quot;25%###BOT_TEXT###quot;>Logical AND (&&)</td>" + 23 "<td>false && false: " + ( false && false ) + 24 "<br />false && true: " + ( false && true ) + 25 "<br />true && false: " + ( true && false ) + . 9. 20 21 document. 16 17 document.html 6 --> <!-.html LogicalOperators.org/TR/xhtml1/DTD/xhtml1-strict.Fig.w3.dtd"> 4 5 <!-.writeln( 15 "<table border = ###BOT_TEXT###quot;1###BOT_TEXT###quot; width = ###BOT_TEXT###quot;100%###BOT_TEXT###quot;>" ).1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.org/1999/xhtml"> <head> <title>Demonstrating the Logical Operators</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 document.0 Strict//EN" 3 "http://www.Demonstrating Logical Operators (1 of 2) --> 7 8 9 10 <html xmlns = "http://www.18: LogicalOperators.w3.writeln( 18 "<caption>Demonstrating Logical " + 19 "Operators</caption" ).

28 29 document.writeln( "</table>" ).writeln( 38 "<tr><td width = ###BOT_TEXT###quot;25%###BOT_TEXT###quot;>Logical NOT (!)</td>" + 39 "<td>!false: " + ( !false ) + 40 "<br />!true: " + ( !true ) + "</td>" ).html (2 of 2) 36 37 document.26 "<br />true && true: " + ( true && true ) + 27 "</td>" ). LogicalOperators.writeln( 30 "<tr><td width = ###BOT_TEXT###quot;25%###BOT_TEXT###quot;>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>" ). 43 // --> 44 </script> 45 46 </head><body></body> 47 </html> . 41 42 document.

.

Logical Operators .