Javascript: Control Statements
Chapter 7: Javascript: Control Statements
CS 80: Internet Programming
Instructor: Mark Edmonds
Background and Terminology
Algorithm
What is an algorithm?
A procedure for solving a problem. Consists of:
1. The actions to be executed
2. The order in which the actions are to be executed
Notice: this definition has nothing to do with a programming language, program statements,
etc.
*
We are abstracting away code into problem solving
Background and Terminology
Pseudocode
A way to express the essence of an algorithm without using a programming language
Informally, it is a way to express what and how the algorithm does something, but doesn’t specify
syntax
Why is this useful?
Syntax is cumbersome, many trivial details of the code do not correspond to the overarching
problem the algorithm solves
Background and Terminology
Pseudocode
Example: Leap year
1 // leap year pseudocode
2 if year is divisible by 400 then
3 is_leap_year
4 else if year is divisible by 100 then
5 not_leap_year
6 else if year is divisible by 4 then
7 is_leap_year
Mark Edmonds 1
Javascript: Control Statements
8 else
9 not_leap_year
This is in between code and English!
This can be directly converted to code, regardless of programming language used
Background and Terminology
Pseudocode
There are multiple ways of writing the same program, and we can write multiple versions of
pseudocode
Example: Compound conditional leap year:
1 leapYear = false
2 if year % 400 == 0
3 leapYear = true
4 else if year % 100 != 0 and year % 4 == 0
5 leapYear = true
Notice we are just describing the logic behind the program without consideration of syntax
Background and Terminology
Pseudocode
Another example of the same logic encoded in dierent pseudocode:
1 leapYear = false
2 if year % 400 == 0 or (year % 100 != 0 and year % 4 == 0)
3 leapYear = true
Control Statements
Prior to the if...else statement, our programs executed sequentially
Programs executed from top to bottom
if...else
introduced branching, or a conditional jump, meaning the program would "choose a
fork in the road" based on some boolean e valuation
Branching enables more powerful programs, since the state of particular variables can vary
with each execution
Mark Edmonds 2
Javascript: Control Statements
if...else
gave us control over what program statements to executes for cases we cared
about
Control Statements
History lesson: the goto statement
Instructed a program to jump to a particular line in the program
Think of a function: "goto the starting line of the called function" and terminates with a
"goto to the next line of the calling function"
This is a largely deprecated programming practice
Enabled a "spaghetti programming" where a program was like a whole bunch of spaghetti
laid out, with each piece of spaghetti representing a goto statement
Control Statements
Now, imperative languages (Javascript, C, C++, Java, Python, ...) use structed programming that
consists of three control structures
1. sequence structure - execute the program linearly, one right aer another
2. selection structure - select or ignore a program statement (if...else)
3.
repetition structure - repeat the program statement(s) a certain number of times (
while,
do...while, for, for...in)
Control Statements
We can model the control structure of a program with graphical models that show the control
flow of the program
A flowchart of the possible program executions
Useful for modeling sub components of a program, but infeasible to model an entire pro-
gram’s execution
Control Statements
Javascript Keywords
Mark Edmonds 3
Javascript: Control Statements
Figure 1: Javascript keywords
Control Statements
if statement
Already covered
Important new terminology in terms of control flow:
*
if
is a single-selection statement. It selects or ignores a single action (program state-
ment(s))
*
We can think of an if statement as having a single entry point and single exit point
Control Statements
if...else statement
Already covered
if...else is a double-selection statement
*
Selects among two actions
Control Statements
Ternary Operator (Conditional Operator)
Mark Edmonds 4
Javascript: Control Statements
We can shorthand the if else statement with a ternary operator of the following form:
1 cond ? true_action : false_action
Example:
1 document.writeln( student_grade >= 60 ? "Passed" : "Failed" ); //
immediately using the result
2 var courseResult = student_grade >= 60 ? "Passed" : "Failed"; //
assignment to the result
Control Statements
Ternary Operator (Conditional Operator)
Dierences with if...else
Ternary operator returns a value
This is how the above two examples work (collapse/evaluate the ternary to see...)
*
E.g. if
student_grade
was 50, this the same as calling
document.writeln("
Failed"); or assigning pass_fail = "Failed";
Dangling elses
We are permitted to write nested if...else statements
We also don’t have to include the curly braces {}, which start a block statement
Block statements are groupings of program statements
You can think of them like compound statements, in the same sense of compound condi-
tionals
Dangling elses
Variable Scope
Example block statement:
1 // javascript blocks and scope
2 var a1 = 3;
3 {
4 var a2 = 5;
5 }
6 console.log(a1 + a2);
Mark Edmonds 5
Javascript: Control Statements
This behavior is dierent from C/C++!
Block statements do not introduce scope
Dangling elses
Variable Scope
Scope is the "lifetime of a variable"
When a variable/function goes out of scope, it is not valid to use that variable or function
again
In the example above, an equivalent C/C++ code segement would fail to compile because
a2 would be out of scope
The scope of a2 would be from its declaration to its closing curly brace
Back to why this matters for if...else...
Dangling elses
If we don’t include the curly braces, we have an implicit block statement
But what problems might we encounter with nested if...elses?
Dangling elses
Consider the following possibilities (hint: the indentation does not aect the semantic meaning)
1 // dangling else's
2 if ( x > 5 )
3 if ( y > 5 )
4 document.writeln( "<p>x and y are &gt; 5</p>" );
5 else
6 document.writeln( "<p>x is &lt;= 5</p>" );
1 // dangling else's
2 if ( x > 5 )
3 if ( y > 5 )
4 document.writeln( "<p>x and y are &gt; 5</p>" );
5 else
6 document.writeln( "<p>x is &lt;= 5</p>" );
Mark Edmonds 6
Javascript: Control Statements
Dangling elses
The first indentation reflects the semantics. Why?
1 // dangling else's
2 if ( x > 5 )
3 if ( y > 5 )
4 document.writeln( "<p>x and y are &gt; 5</p>" );
5 else
6 document.writeln( "<p>x is &lt;= 5</p>" );
1 // dangling else's
2 if ( x > 5 )
3 if ( y > 5 )
4 document.writeln( "<p>x and y are &gt; 5</p>" );
5 else
6 document.writeln( "<p>x is &lt;= 5</p>" );
Dangling elses
If there is no included block statements, a single statement is grouped to the if
if...else is considered a single conditional statement
This is part of JavaScript syntax, and is very common across programming languages
What’s the solution?
Using block statements fixes this problem because it enforces which
if
the
else
belongs
to
Dangling elses
Fix:
1 // dangling else's
2 if ( x > 5 ){
3 if ( y > 5 )
4 document.writeln( "<p>x and y are &gt; 5</p>" );
5 } else
6 document.writeln( "<p>x is &lt;= 5</p>" );
I (personally) recommend always wrapping conditionals, loops, etc. with block statements:
1 // dangling else's
Mark Edmonds 7
Javascript: Control Statements
2 if ( x > 5 ) {
3 if ( y > 5 ){
4 document.writeln( "<p>x and y are &gt; 5</p>" );
5 }
6 } else {
7 document.writeln( "<p>x is &lt;= 5</p>" );
8 }
Dangling elses
Consider another error-prone situation:
1 // dangling else's
2 if ( grade >= 60 )
3 document.writeln( "<p>Passed</p>" );
4 else
5 document.writeln( "<p>Failed</p>" );
6 document.writeln( "<p>You must take this course again.</p>" );
Under what circumstances will "You must take this course again" be printed to the user?
Dangling elses
1 // dangling else's
2 if ( grade >= 60 )
3 document.writeln( "<p>Passed</p>" );
4 else
5 document.writeln( "<p>Failed</p>" );
6 document.writeln( "<p>You must take this course again.</p>" );
The Javascript interpreter does not read indentation for semantics
The last line is not associated with the else
Semantic version:
1 // dangling else's
2 if ( grade >= 60 )
3 document.writeln( "<p>Passed</p>" );
4 else
5 document.writeln( "<p>Failed</p>" );
6 document.writeln( "<p>You must take this course again.</p>" );
Mark Edmonds 8
Javascript: Control Statements
Dangling elses
Fix:
1 // dangling else's
2 if ( grade >= 60 )
3 document.writeln( "<p>Passed</p>" );
4 else {
5 document.writeln( "<p>Failed</p>" );
6 document.writeln( "<p>You must take this course again.</p>" );
7 }
Dangling elses
The main point: don’t trust indentation!
Use explicit block statements (through curly braces)
*
You must use a block if you have more than a single statement under your condition-
al/loop
*
I do this all the time, no matter. I personally belie ve it oers a cleaner, more consistent
code style that has better defined semantics
Dangling elses
Technical semantics (the actual logic here):
if and else will associate with the next statement
That statement can be a single program statement, or a compound statement
*
By making the next statement a block statement, we avoid the problem completely,
even if we only execute one statement in that block statement.
·
Removes ambiguity in all cases while adding minimal amount of lines to your
program (not that ever print source code anyway, so the length of your program
doesn’t really matter)
Errors
When debugging, we need to evaluate what is causing the problem in our program and how we
can fix it
Three main types of errors:
Syntax errors - invalid code. The compiler/interpreter cannot succesfully execute the pro-
gram. Will be detected by the computer. Basically means you violated the rules of the
Mark Edmonds 9
Javascript: Control Statements
language. Example: forgetting to put a closing curly brace at the end of an if...else.
Semantic errors - valid code, but does not produce the results you expect. Example: using
the wrong variable or operator somewhere in your code
Design errors - valid code and produces the results you expect. However, your understanding
of the problem is wrong. Example: using the wrong forumla for something.
Errors - Semantic & Design
Semantic and design errors are very similar but have dierent implications for debugging
A semantic error means we understand the problem and need to adjust our code to reflect
that understanding
A design error means we don’t understand the problem and will never be able to produce a
working program
A design error is a more significant problem than semantic error!
Fixing Errors
Ways to fix errors:
Syntax error: computer will usually give a hint as to what’s causing the problem. Go inspect
your code to see what might be wrong (generally easy, but can be incredibly frustrating)
Semantic error: assuming you have correct pseudocode, something in your program doesn’t
match the pseudocode. Compare the two and make sure the operations match up. This is
when you can’t believe you’ve wasted an hour verifying your pseudocode matches your
code but you mistyped a + for a *.
Design error: Your pseudocode is wrong. Fix the pseudocode first. There’s no specific
advice to give since this error is always problem-specific. This is when you email your
professor/supervisor/(maybe) customer for guidance.
Reptition (loops)
Repeat an action a number of times while a condition is true
Example shopping pseudocode:
1 While there are more items on my shopping list
2 Purchase next item and cross it off my list
When the condition becomes false, the loop exits
Critical part: the loop must do something that will eventually cause the condition to be false
Mark Edmonds 10
Javascript: Control Statements
Otherwise, we are stuck in an infinite loop!
Reptition (loops)
Example for shopping:
1 // shopping list
2 var shopping_list = ["pants", "grocercies", "car"];
3 var i = 0;
4 // purchase all items in the list
5 while(i < shopping_list.length)
6 {
7 purchase(shopping_list[i]); // purchase the item
8 i = i + 1; // move to the next item
9 }
10 function purchase(item){
11 window.alert("Purchased " + item);
12 }
Reptition (loops)
If you think visually, consider the following code flowchart
1 var product = 2;
2 while ( product <= 1000 )
3 {
4 product = 2 * product;
5 }
Reptition (loops)
If you think visually, consider the following code + flowchart
Mark Edmonds 11
Javascript: Control Statements
We can think about a loop as a repeated cycle in a flowchart until a condition becomes false
Exercise
Class Average
Write pseudocode and javascript to average a class’s scores on an exam.
The program should prompt the user for the number of students in the class, then ask for each
score.
The scores should be printed nicely into a table with the average at the bottom.
Exercise
Class Average
Pseudocode:
1 Set total to zero
2 Set grade counter to zero
3 Input number of students
4 Print table header
5 While grade counter is less than number of students
6 Input the next grade
7 Add the grade into the total
8 Add one to the grade counter
9 Print grade to table
10 Set the class average to the total divided by number of students
11 Print the class average to table
Mark Edmonds 12
Javascript: Control Statements
Exercise: class_average.html
1 <!DOCTYPE html>
2 <html>
3
4 <head>
5 <meta charset="utf-8">
6 <title>Class Average Problem</title>
7 <style>
8 table,
9 th,
10 td {
11 border: 1px solid black;
12 }
13
14 table {
15 border-collapse: collapse;
16 }
17
18 th,
19 td {
20 padding: 15px;
21 text-align: left;
22 }
23 </style>
24 <script>
25 var total; // sum of grades
26 var gradeCounter; // number of grades entered
27 var grade; // grade typed by user
28 var average; // average of all grades
29 // initialization phase
30 total = 0; // clear total
31 gradeCounter = 0;
32 var numStudents = window.prompt("Enter the number of students: ", "
0");
33 numStudents = parseInt(numStudents);
34
35 if (numStudents == 0)
36 {
37 document.writeln("The number of students is 0");
38 }
39 else
40 {
Mark Edmonds 13
Javascript: Control Statements
41 //setup table
42 document.writeln("<table>");
43 document.writeln("<caption><strong>Exam scores</strong></caption>
");
44 document.writeln("<thead>\n<tr>\n<th>Student Number</th>\n<th>
Grade</th>\n</thead>");
45 document.writeln("<tbody>");
46
47 // loop, processing phase
48 while (gradeCounter < numStudents) {
49 // prompt for input and read grade from user
50 grade = window.prompt("Enter integer grade:", "0");
51 // convert grade from a string to an integer
52 grade = parseInt(grade);
53 // add gradeValue to total
54 total = total + grade;
55 // add 1 to gradeCounter
56 gradeCounter = gradeCounter + 1;
57 // add data to table
58 document.writeln("<tr>\n<td>" + gradeCounter + "</td>\n<td>" +
grade + "</td>\n</tr>");
59 } // end while
60
61 // calculate the average
62 average = total / numStudents;
63 // display average of exam grades
64 document.writeln("</tbody>");
65 document.writeln("<tfoot>\n<tr>\n<th>Average</th>\n<th>" +
average + "</th>\n</tr>\n</tfoot>");
66 document.writeln("</table>");
67 }
68 </script>
69 </head>
70
71 <body>
72 </body>
73
74 </html>
Exercise: class_average_functions.html
Next, let’s consider breaking our program into multiple parts.
Mark Edmonds 14
Javascript: Control Statements
We’ll have one function to collect the grades
Another function to display the grades
And another function to calculate the average
Exercise: class_average_functions.html
1 <!DOCTYPE html>
2 <html>
3
4 <head>
5 <meta charset="utf-8">
6 <title>Class Average Problem</title>
7 <style>
8 table,
9 th,
10 td {
11 border: 1px solid black;
12 }
13
14 table {
15 border-collapse: collapse;
16 }
17
18 th,
19 td {
20 padding: 15px;
21 text-align: left;
22 }
23 </style>
24 <script>
25 function collectGrades() {
26 var total; // sum of grades
27 var gradeCounter; // number of grades entered
28 var grade; // grade typed by user
29 var average; // average of all grades
30 var grades = []; // array to store grades
31 // initialization phase
32 total = 0; // clear total
33 gradeCounter = 0;
34 var numStudents = window.prompt("Enter the number of students: ",
"0");
35 numStudents = parseInt(numStudents);
Mark Edmonds 15
Javascript: Control Statements
36
37 // loop, processing phase
38 while (gradeCounter < numStudents) {
39 // prompt for input and read grade from user
40 grade = window.prompt("Enter integer grade:", "0");
41 // convert grade from a string to an integer
42 grade = parseInt(grade);
43 // add gradeValue to total
44 total = total + grade;
45 // add 1 to gradeCounter
46 gradeCounter = gradeCounter + 1;
47 // add grade to our grades array
48 grades.push(grade);
49 } // end while
50 return grades;
51 }
52
53 function displayGrades(grades, average){
54 if (grades.length == 0)
55 {
56 document.writeln("The number of students is 0");
57 return;
58 }
59 //setup table
60 document.writeln("<table>");
61 document.writeln("<caption><strong>Exam scores</strong></caption>
");
62 document.writeln("<thead>\n<tr>\n<th>Student Number</th>\n<th>
Grade</th>\n</thead>");
63 document.writeln("<tbody>");
64
65 // loop, processing phase
66 for(var i = 0; i < grades.length; i++) {
67 // add data to table
68 document.writeln("<tr>\n<td>" + i + "</td>\n<td>" + grades[i] +
"</td>\n</tr>");
69 } // end while
70
71 // display average of exam grades
72 document.writeln("</tbody>");
73 document.writeln("<tfoot>\n<tr>\n<th>Average</th>\n<th>" +
average + "</th>\n</tr>\n</tfoot>");
74 document.writeln("</table>");
Mark Edmonds 16
Javascript: Control Statements
75 }
76
77 function calculateAverage(array){
78 // loop over grades to calculate average
79 var average = 0;
80 if (array.length > 0){
81 for(var i = 0; i < array.length; i++){
82 average += array[i];
83 }
84 average /= array.length;
85 }
86 return average;
87 }
88
89 var grades = collectGrades();
90
91 var average = calculateAverage(grades);
92
93 displayGrades(grades, average);
94 </script>
95 </head>
96
97 <body>
98 </body>
99
100 </html>
Exercise
Real Estate License
A college oers a course that prepares students for the state licensing exam for real estate brokers.
Last year, 10 of the students who completed this course took the licensing exam. Naturally, the
college wants to know how well its students performed.
You’ve been asked to write a script to summarize the results. You’ve been given a list of these 10
students. Next to each name is written a 1 if the student passed the exam and a 2 if the student
failed.
Exercise
Real Estate License
Mark Edmonds 17
Javascript: Control Statements
Your script should analyze the results of the exam as follows:
1.
Input each test result (i.e., a 1 or a 2). Display the message “Enter result” on the screen each
time the script requests another test result.
2. Count the number of test results of each type.
3.
Display a summary of the test results indicating the number of students who passed and
the number of students who failed.
4. If more than eight students passed the exam, print the message “Bonus to instructor!
Exercise
Real Estate License
Pseudocode:
1 Initialize passes to zero
2 Initialize failures to zero
3 Initialize student to zero
4 While student counter is less than ten
5 Input the next exam result
6 If the student passed
7 Add one to passes
8 Else
9 Add one to failures
10 Add one to student counter
11 Print the number of passes
12 Print the number of failures
13 If more than eight students passed
14 Print "Bonus to Instructor!";
Exercise: bonus.html
1 <!DOCTYPE html>
2 <!-- Fig. 7.11: analysis.html -->
3 <!-- Examination-results calculation. -->
4 <html>
5
6 <head>
7 <meta charset="utf-8">
8 <title>Analysis of Examination Results</title>
9 <script>
10 // initializing variables in declarations
Mark Edmonds 18
Javascript: Control Statements
11 var passes = 0; // number of passes
12 var failures = 0; // number of failures
13 var student = 0; // student counter
14 var result; // an exam result
15 // process 10 students; counter-controlled loop
16 while (student < 10) {
17 result = window.prompt("Enter result (1=pass,2=fail)", "0");
18 if (result == "1")
19 {
20 passes = passes + 1;
21 }
22 else
23 {
24 failures = failures + 1;
25 }
26 student = student + 1;
27 } // end while
28 document.writeln("<h1>Examination Results</h1>");
29 document.writeln("<p>Passed: " + passes +"; Failed: " + failures +
"</p>");
30
31 if (passes > 8)
32 {
33 document.writeln("<p>Bonus to instructor!</p>");
34 }
35 </script>
36 </head>
37
38 <body></body>
39
40 </html>
Assignment Operators
Modifying a variable (changing its value) is extremely common. We have a shorthand way doing
this:
1 c = c + 3;
2 c += 3;
More generally, any statement of the form:
Mark Edmonds 19
Javascript: Control Statements
1 variable = variable operator expression;
Can always be written as:
1 variable operator= expression; // operator could be +, -, *, /, %
2 // for example
3 c *= 4; // multiply by 4
Assignment Operators
Figure 2: Assignment operators
Mark Edmonds 20
Javascript: Control Statements
Increment and Decrement
Figure 3: Increment and decrement operators
Increment and Decrement
Key dierence:
pre changes the value, then returns the new value
post returns the current value, then change the value
These operators break PEMDAS; they have a higher precedence than *, /, %
Increment and Decrement
Consider the following. Carefully consider the value of counter1 and counter2:
1 var a = 10;
2 var counter1 = 0;
3 var counter2 = 0;
4 var i = 0;
5 while(counter1++ < a)
6 {
7 //loop 1
8 console.log("Loop 1, i: ", i);
9 i++;
10 }
11 i=0;
12 while(++counter2 < a)
13 {
14 //loop 2
Mark Edmonds 21
Javascript: Control Statements
15 console.log("Loop 2, i: ", i);
16 i++;
17 }
18 console.log(counter1);
19 console.log(counter2);
Increment and Decrement
What will be the final value of counter1 and counter2?
Increment and Decrement
What will be the final value of counter1 and counter2?
counter1
will be 11 (loop 1 runs 10 times, but counter1 is incremented an extra time (postin-
crement))
counter2 will be 10 (loop 2 runs 9 times)
Additional Repetition Structures
for
Functionally equivalent to while
1 for(initialization_statement; loop_condition; loop_end_statement)
2 {
3 // loop body
4 }
5 // in practice
6 for (var i = 0; i < 10; i++)
7 {
8 // loop body
9 }
10 // which is the same as
11 var i = 0;
12 while (i < 10){
13 i++;
14 }
Additional Repetition Structures
do...while
Mark Edmonds 22
Javascript: Control Statements
Like a while loop, but guarantees that the loop will execute at least once
Condition is checked at the end of the loop
1 var i = 0;
2 do {
3 // loop body
4 i++;
5 }
6 while(i < 10);
Example: sortedList.html
1 <!doctype html>
2
3 <!-- sortedList.html -->
4 <!-- Input several names and display them in a sorted list. -->
5 <html>
6 <head>
7 <meta charset="utf-8" />
8 <title>Sorted List</title>
9 </head>
10 <body>
11 <h1>People</h1>
12 <ol id="ol"></ol>
13 <script>
14 var name; // name entry
15 var people = []; // array of people
16
17 // get names
18 while (true) {
19 name = prompt("Name: ", "Done");
20 if (name === "Done") {
21 break; // stop getting names
22 }
23 people.push(name); // add name to end of array
24 }
25
26 // sort the array
27 people.sort();
28
29 // output the list
Mark Edmonds 23
Javascript: Control Statements
30 document.getElementById("ol").innerHTML = "<li>" + people.join("</li><
li>") + "</li>";
31 </script>
32 </body>
33 </html>
Mark Edmonds 24