JavaScript V
Conditional Execution
Outline

Conditional statement




If-then
If-then-else
Nested If
Boolean expressions
Program execution

Unconditional 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

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
Need not be a single step
 might be a chunk of code controlled by the condition
 call the "body"
Examples

if due date on book is before today's date


if day of the week is not sunday or holiday


charge overdue fee
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
JavaScript

if statement



if (condition) statement or
if (condition) { statements }
Example
if (dateToday > dueDate)
bookOverdue = true;

or
if (dateToday > dueDate)
{
bookOverdue = true;
calculateFine (dateToday, dueDate);
...
}
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
program step 1
If (condition)
conditional true step(s)
else
condition false step(s)
program step 2
program step 3
program step 4
Examples

if the title is a new release



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
JavaScript

if statement
if (condition) {
then part
}
else {
else part
}

Example
if (newRelease(title)) {
charge = 3.00;
lendingPeriod = 2;
}
else {
charge = 2.00;
lendingPeriod = 5;
}
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
9
JavaScript

if statement
if (condition) {
then part
}
else {
else part
}

Example
if (newRelease(title)) {
charge = 3.00;
lendingPeriod = 2;
}
else {
charge = 2.00;
lendingPeriod = 5;
}
Stylistic issues

Where to put brackets

I prefer after condition
if (condition) {
... body ...
}
else {
... body ...
}

Some prefer on separate lines
if (condition)
{
... body ...
} else
{
... body ...
}

In some cases, you might put whole statement on one line
if (condition) { ... body ... }
If Statement Examples
an if statement is known as a control statement, since its purpose is to control the
execution of other statements
12
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
13
Example



ifdemo.html
ifdemo2.html (with else)
chill.html
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...;
}
}
else {
... wind chill undefined ...
}

Example: chill2.html
Exercise
if (x >= y) {
if (x*10 < 100) {
document.write(“ONE”);
}
else {
document.write(“TWO”);
}
}
else {
document.write(“THREE”);
}
x = 0;
x = 0;
x = 9;
x = 22;
y = 5;
y = -5;
y = 9;
y = 21;
output  ?
output  ?
output  ?
output  ?
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
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
18
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
19
Die Roll Page
RandomInt function from
random.js is used to select the random
roll
the
depending
on the roll value, the correct
image is displayed
since
more than two possibilities, a
cascading if-else is needed
20
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
}
= "http://dave-reed.com/book/Images/die1.gif";
= "http://dave-reed.com/book/Images/die2.gif";
= "http://dave-reed.com/book/Images/die3.gif";
= "http://dave-reed.com/book/Images/die4.gif";
= "http://dave-reed.com/book/Images/die5.gif";
= "http://dave-reed.com/book/Images/die6.gif";
this entire cascading if-else structure could be replaced by the following:
document.getElementById('die').src =
"http://dave-reed.com/book/Images/die" + roll + ".gif";
21
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
22
Examples

dice.html


twodice.html




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
Equality operators





Equal
Not equal
Inequality
==
!=
>, >=, <, <=
These are operators just like +, -, etc.
What data type do they return?

i<5
Decision Making:
Equality and Relational Operators
S ta n d a rd a lg e b ra ic
e q u a lity o p e ra to r o r
re la tio n a l o p e ra to r
E quality operators
Ja va S crip t e q u a lity S a m p le
o r re la tio n a l
Ja va S crip t
o p e ra to r
co n d itio n
M e a n in g o f
Ja va S crip t
co n d itio n
=
?
R elational operators
>
<
==
!=
x == y
x != y
x is equal to y
x is not equal to y
>
<
>=
x > y
x < y
x >= y
<=
x <= y
x is greater than y
x is less than y
x is greater than or
equal to y
x is less than or
equal to y
F ig . 7 .1 5 E q u a lity a n d re la tio n a l o p e ra to rs.
If Statement Gotcha 1
Type Sensitivity

The result of an inequality depend on data
type


100 > 18
"100" < "18"
If Statement Gotcha 2
Equality vs assignment

Equality test (d == 0)


Boolean value
Assignment (d = 0)

the assignment statement also has a value



bad language design!
Unexpected behavior

if (done = false)



.. do something ..
never executed
Worse yet


"", 0 are automatically converted to false
if (p = 5)



whatever the new value is
.. do something ..
always executed
Check that if statements only use the equality operator ==
Boolean Operators

&&


||


and
or
!

not
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)
Other Examples
die1 = RollDie();
die2 = RollDie();






doubles?
total is 7?
roll is a 1 and 1?
roll contains a 3?
die1 == die2
die1 + die2 == 7
(die1 == 1) && (die2 == 1)
(die1 == 3) || (die2 == 3)
total is 7 or 11?
 (die1 + die2 == 7) || (die1 + die2) == 11
twodice.html

In-class Exercise: with double counter?
Descargar

Web Design