Lesson 15: Conditional Execution & If Statements

Due by the beginning of class on Wednesday, Mar. 3

So far, all the JavaScript code that you have written has been executed unconditionally. When you wrote a sequence of statements, those statements were executed one after another, in order. Similarly, a call to a function caused control to transfer to that function following a well-defined sequence of steps. And while for loops caused statements to be executed over and over, they always did so a prescribed number of times in a specific order.

Many programming tasks, however, require conditional control, that is, the ability to react differently based upon some condition. For example, consider the task of assigning students letter grades. Depending upon what the student's average is, a different letter grade must be assigned (e.g., 90 to 100 is an A, 80 to 89 is a B, etc.). In this lesson, you will be introduced to the if statement which is used to perform such conditional execution. Based upon some condition, an if statement can choose among alternative sequences of code to execute, or even choose to execute no code at all.


If Statements

Conditional execution refers to the ability to execute a statement or sequence of statements only if some condition holds. The simplest form of conditional statement involves only one possible action. For example, printing out a message when the value of a variable is positive. However, conditional execution can also involve alternatives based on the same or related conditions. For example, we might want to print one message if the variable has a positive value and another message if it doesn't. This type of conditional execution in JavaScript is performed using if statements.

The following are examples if statements which perform the conditional executions described above. if (number > 0) { document.write(number + " is a positive value.<BR>"); } if (number > 0) { document.write(number + " is a positive value.<BR>"); } else { document.write(number + " is a NOT positive value.<BR>"); } In the first statement, the write statement is executed only if the condition (number > 0) holds (i.e. it is true). The second statement includes an else case which specifies the action to be taken if the condition does not hold (i.e., it is false number <= 0).

The general form of an if statement is as follows, where the else case is optional:

if (CONDITION) { STATEMENTS_IF_TRUE } else { STATEMENTS_IF_FALSE } When evaluating an if statement, JavaScript first evaluates the CONDITION which appears in parentheses in the first line. If the CONDITION is true the code immediately below (inside the curly-braces) is executed. If the CONDITION is false and there is an else case, then the code below the else (inside the curly-braces) is executed. Note that if the CONDITION is false and there is no else case, then no statements are executed.

The CONDITION in an if statement can be any boolean expression, that is, any expression that evaluates to either true or false. The following relational operators can be used to build boolean expressions:

   ==     equal to
   !=  not equal to
   <  less than
   <=  less than or equal to
   >  greater than
   >=  greater than or equal to


Exercise 1:     Cut-and-paste the following section of code into the JavaScript interpreter. number = parseFloat( prompt("Enter a number", "") ); if (number > 0) { document.write(number + " is a positive value.<BR>"); } else { document.write(number + " is a NOT positive value.<BR>"); } Execute it once for each of the following input values. Before executing the code, try to predict the output. Then verify your prediction.


Exercise 2:     Cut-and-paste the following section of code into the JavaScript interpreter. word = prompt("Enter a word", ""); if (word != "foo") { document.write("You ain't got foo!<BR>"); } Execute it once for each of the following input values. Before executing the code, try to predict the output. Then verify your prediction.


Exercise 3:     Cut-and-paste the following section of code into the JavaScript interpreter. num1 = parseFloat( prompt("Enter a number", "") ); num2 = parseFloat( prompt("Enter another number", "") ); if (num1 % num2 == 0) { document.write(num2 + " divides " + num1 + " evenly<BR>"); } else { document.write(num2 + " does not divide " + num1 + " evenly<BR>"); } Execute it once for each of the following input values. Before executing the code, try to predict the output. Then verify your prediction.


Exercise 4:     Write a code segment which prompts the user for their name, and then displays a special greeting to that person if their name is the same as yours. If the name entered by the user is anything other than your name, your code should not produce any output.


Exercise 5:     At Dickinson, "roll call" grades are assigned around midterm to help students to assess their performance. A common rule-of-thumb is to consider a grade of C or better to be Satisfactory, while C- or worse is Unsatisfactory. Write a code segment which prompts the user for their average, and then displays a message assessing their performance. If their average is 73 or higher, they should receive a Satisfactory rating, otherwise Unsatisfactory.


Cascading If Statements

In its simplest form, an if statement can decide between executing a sequence of statements once, or not at all. For example, in the first example of an if statement above, the code will either display a message on the condition that a number is positive, or else it will do nothing at all. Using an else case, an if statement can decide between two alternative sections of code, as in the example where a different message is displayed for positive and non-positive numbers.

There are examples, however, in which more than two alternatives must be considered. For example, suppose you were to write code for assigning letter grades in a class based on the student's final class average. In a rigid scoring system, any grade of 90 or better would receive an "A", any grade between 80 and 89 a "B", and so on down through "C", "D", and "F". Thus, there are 5 alternatives for assigning the grade, conditional upon where the student's average.

In JavaScript, arbitrary numbers of alternative cases can be considered using a sequence of nested if statements (shown on the left). A more compact and easer to read form of these nested if statments is the cascading if statement (shown on the right). A cascading if statement is really nothing more than nested if statements, formatted to be easier to read.

Nested if Statements Cascading if Statements
if (grade >= 90) { letterGrade = "A"; } else { if (grade >= 80) { letterGrade = "B"; } else { if (grade >= 70) { letterGrade = "C"; } else { if (grade >= 60) { letterGrade = "D"; } else { letterGrade = "F"; } } } } if (grade >= 90) { letterGrade = "A"; } else if (grade >= 80) { letterGrade = "B"; } else if (grade >= 70) { letterGrade = "C"; } else if (grade >= 60) { letterGrade = "D"; } else { letterGrade = "F"; }

The term cascading refers to the way that control cascades down the statement like water down a waterfall. The top-most test is evaluated first, in this case (grade >= 90). If this test succeeds, then the corresponding statements are executed and control passes to the end of the if statement. If not, then control cascades down to the next if test, in this case (grade >= 80). In general, control cascades down the statement from one test to another until one succeeds or the end of the statement is reached.


Exercise 6:     Cut-and-paste the above cascading if statement into the interpreter. Add a prompt which asks the user for their number grade and reads that value into the grade variable. Similarly, add a write statement at the end to display the letter grade. Execute the code on each of the following grades and report the result.


Exercise 7:     Cut-and-paste the code from Exercise 1 which displayed whether a number is positive or not. Modify that statement so that it prints one of three messages, stating whether the number is positive, negative, or zero. Test your new statement on a variety of numbers to be sure that it works correctly.


Nesting Control Statements

Once written, a control statement is just like any other statement (e.g., an assignment or a call to document.write). In particular, you can nest a control statement inside another control statement. You have already seen this with a cascading if statement, which is really just a series of nested if statements. The same holds for the other control statement you know, the for loop. You can nest one for loop inside another, although this is usually avoided since tracing the flow of control can become tricky. You can also nest an if statement inside a for loop, and vice versa.


Exercise 8:     Consider the following segment of JavaScript code. for (i = 1; i <= 20; i++) { if (i % 2 == 0) { document.write("Pass " + i + "<BR>"); } } Before executing this code, try to predict what output it will produce. Then, cut-and-paste the code into the interpreter and verify your prediction.


Exercise 9:     Write a segment of JavaScript code that will display the sum of all the even numbers from 2 up to a certain maximum. That maximum should be prompted for and entered by the user. Your code should contain a for loop to range through the numbers and add them together, and an if statement to consider only those numbers in the range that are even. Hint: refer to the code in the previous exercise.


Exercise 10:     Consider the following code segment, which prints a table of powers of 2. The number of rows in the table is specified by the user in response to a prompt. size = parseFloat( prompt("Enter the table size", "") ); document.write("n 2<SUP>n</SUP><BR>"); document.write("-------<BR>"); for (row = 1; row <= size; row++) { document.write(row + " " + Math.pow(2, row) + "<BR>"); } Now consider what would happen if the user were to enter a negative number or zero at the prompt. The for loop would produce no output, since the number of loops specified would be less than 1. The two lines preceding the loop, however, would display the table heading even if there was to be no data in the table.

Add an appropriate if statement to this code to verify that the number entered by the user is indeed 1 or greater. If so, it should proceed to display the table as is. If not, it should display an error message and avoid executing any of the table code.


Lesson Summary


Solutions to odd numbered exercises (posted late afternoon of due date).