Presentation is loading. Please wait.

Presentation is loading. Please wait.

Conditional Execution

Similar presentations


Presentation on theme: "Conditional Execution"— Presentation transcript:

1 Conditional Execution
JavaScript V Conditional Execution

2 Outline Conditional statement Nested If Boolean expressions If-then
If-then-else Nested If Boolean expressions

3 Program execution Unconditional execution Conditional execution
interpreter executes each line in sequence Conditional execution evaluate a test execute code only if test is true we can think of this as one step not always executed Need not be a single step might be a chunk of code controlled by the condition call the "body" program step 1 program step 2 program step 3 program step 4 program step 5 condition conditional step program step 2 program step 3 program step 4

4 Examples if due date on book is before today's date
charge overdue fee if day of the week is not sunday or holiday parking meter must be used if even day of the month and date between Nov 1 and April 1 car will be ticketed and towed

5 JavaScript if statement Example if (condition) statement or
if (condition) { statements } Example if (dateToday > dueDate) bookOverdue = true; or { calculateFine (dateToday, dueDate); ... }

6 If-then-else Conditional execution evaluate a test
execute one piece of code if test is true execute another piece if test is false we can think of this as one step one part or the other will be executed If (condition) conditional true step(s) else condition false step(s) program step 2 program step 3 program step 4 program step 1

7 Examples if the title is a new release if the answer is correct
then charge $3.00 and lending period is 2 days else charge $2.00 and lending period is 5 days if the answer is correct then add 1 to score else print help message

8 JavaScript if statement Example if (condition) { then part } else {
else part Example if (newRelease(title)) { charge = 3.00; lendingPeriod = 2; charge = 2.00; lendingPeriod = 5;

9 Boolean Tests the test that controls an if statement can be any boolean expression (i.e., an expression that evaluates to either true or false) boolean tests are formed using relational operators because they test the relationships between values NOTE: == is for comparisons = is for assignments the boolean test in an if statement determines the code that will be executed if the test is true, then the code inside the subsequent curly braces will execute if the test is false, then the code inside the curly braces following the else will execute note that if the test is false and there is no else case, the program moves on to the statement directly after the if

10 JavaScript if statement Example if (condition) { then part } else {
else part Example if (newRelease(title)) { charge = 3.00; lendingPeriod = 2; charge = 2.00; lendingPeriod = 5;

11 Stylistic issues Where to put brackets I prefer after condition
if (condition) { ... body ... } else { Some prefer on separate lines if (condition) { } else In some cases, you might put whole statement on one line if (condition) { ... body ... }

12 If Statement Examples an if statement is known as a control statement, since its purpose is to control the execution of other statements

13 Accessing Text Fields recall that values entered via text boxes/areas are always returned as strings if (document.getElementById('age').value >= 18) { alert("You are old enough to vote."); } else { alert("Sorry. You are too young to vote."); will say that a 2-year old can vote, but a 102-year old can't! WHY? if you wish to treat a value obtained from a text box or text area as a number, you must use the parseFloat function to convert it age = parseFloat(document.getElementById('age').value); if (age >= 18) { alert("You are old enough to vote."); } else { alert("Sorry. You are too young to vote."); will behave as expected

14 Example ifdemo.html ifdemo2.html (with else) chill.html

15 Nested If There may be more than two possibilities to be handled
Put one if statement inside another if (temp <= 50) { if (windSpeed <= 3){ windChill = temperature; } else { windChill = ...calculation here...; ... wind chill undefined ... Example: chill2.html

16 Exercise x = 0; y = 5; output  ? x = 0; y = -5; output  ?
if (x >= y) { if (x*10 < 100) { document.write(“ONE”); } else { document.write(“TWO”); document.write(“THREE”); x = 0; y = 5; output  ? x = 0; y = -5; output  ? x = 9; y = 9; output  ? x = 22; y = 21; output  ?

17 Cascading ifs Easier to read than nested style
It is clear that multiple alternatives are involved if (condition1) then { action1 } else if (condition2) then { action2 } else if (condition3) then { action3 } etc Some languages (perl) actually have a special elsif construct

18 A Cleaner Notation when it is necessary to handle a large number of alternatives, nested if-else statements can become cumbersome and unwieldy multiple levels of indentation and curly braces cause the code to look cluttered make it harder to read/understand example: nested if statements vs. a more readable else-if

19 Die Roll Example consider a Web page that simulates the roll of a single die will use an image to display the die will use a button to initiate the die roll when the user clicks the button, a random die roll is selected and the corresponding image is displayed

20 Die Roll Page the RandomInt function from random.js is used to select the random roll depending on the roll value, the correct image is displayed since more than two possibilities, a cascading if-else is needed

21 Generalizing Code note that each case in the cascading if-else follows the same pattern if (roll == 1) { document.getElementById('die').src = " } else if (roll == 2) { document.getElementById('die').src = " else if (roll == 3) { document.getElementById('die').src = " else if (roll == 4) { document.getElementById('die').src = " else if (roll == 5) { document.getElementById('die').src = " else { document.getElementById('die').src = " this entire cascading if-else structure could be replaced by the following: document.getElementById('die').src = " + roll + ".gif";

22 Counters in software applications, if statements are often used to count occurrences of conditional or user-initiated events e.g., count the number of times dice rolls come up doubles e.g., count the number of times the user guesses a number correctly any variable that is used to record occurrences of an event is known as a counter initially, the counter is set to zero each time the specified action occurs, the counter is incremented after a given time period, the value stored in the counter will tell you the number of times the desired event took place

23 Examples dice.html twodice.html Exercise (on your own): Reed style
note image list access with counter In-class Exercise: with double counter? Exercise (on your own): Rewrite wind chill code as cascading ifs

24 Equality operators Equal == Not equal !=
Inequality >, >=, <, <= These are operators just like +, -, etc. What data type do they return? i < 5

25 Decision Making: Equality and Relational Operators

26 If Statement Gotcha 1 Type Sensitivity
The result of an inequality depend on data type 100 > 18 "100" < "18"

27 If Statement Gotcha 2 Equality vs assignment
Equality test (d == 0) Boolean value Assignment (d = 0) the assignment statement also has a value whatever the new value is bad language design! Unexpected behavior if (done = false) .. do something .. never executed Worse yet "", 0 are automatically converted to false if (p = 5) always executed Check that if statements only use the equality operator ==

28 Boolean Operators && and || or ! not

29 Boolean expressions Expressions returning Boolean values
can be used as a condition in an if statement if wind speed above 3 and temperature below 50 calculate wind chill if (windSpeed > 3 && temperature < 50) calculate (windSpeed, temperature)

30 Other Examples twodice.html In-class Exercise: with double counter?
die1 = RollDie(); die2 = RollDie(); doubles? die1 == die2 total is 7? die1 + die2 == 7 roll is a 1 and 1? (die1 == 1) && (die2 == 1) roll contains a 3? (die1 == 3) || (die2 == 3) total is 7 or 11? (die1 + die2 == 7) || (die1 + die2) == 11 twodice.html In-class Exercise: with double counter?


Download ppt "Conditional Execution"

Similar presentations


Ads by Google