javascript logic conditionals, branches, tests… oh my!
Post on 22-Feb-2016
38 Views
Preview:
DESCRIPTION
TRANSCRIPT
JavaScript LogicConditionals, Branches, Tests… Oh My!
Fluency with Information Technology
INFO100 and CSE100
Katherine Deibel
2012-04-30 Katherine Deibel, Fluency in Information Technology 1
JavaScript So Far… Plain text instructions for dynamic pages
In <script type="text/javascript></script> tags Or in a separate file
Variables Boolean, string, or numeral Declared with var
Operators +, -, *, /, % + concatenates strings
2012-04-30 Katherine Deibel, Fluency in Information Technology 2
Katherine Deibel, Fluency in Information Technology 3
Read Line By Line Remember, browsers read HTML, CSS, and
JavaScript line-by-line What if we want the browser to skip a line?
We could put it inside a comment but the browser would just ignore it
What we want is logical branching Example:
If I am out of underwear, do laundryElse put on underwear
2012-04-30
Logic in Programming Many names: conditionals, branches, tests Programs are typically step-to-step and
sequential Branches allow programs to follow different
paths of execution based on User feedback Variable values Comparisons between values
2012-04-30 Katherine Deibel, Fluency in Information Technology 4
Vocabulary Boolean:
a value that is true or false Boolean variable:
a JS variable that has been set to either true or false
[Boolean] test: a computation that returns a Boolean value
2012-04-30 Katherine Deibel, Fluency in Information Technology 5
Conditionals Conditionals test an expression to see
ifit is true or false General Form:
if(<Boolean expression>)<Then statement>;
In JavaScript:if(day == "Monday")
evening_plan = "Watch HIMYM";
2012-04-30 Katherine Deibel, Fluency in Information Technology 6
No ; after if Do not put a semicolon after an if statement:
if(day == "Monday"); BAD!! View the if statement and its following line
as one statement:if(day == "Monday") plan = "HIMYM";
2012-04-30 Katherine Deibel, Fluency in Information Technology 7
Effects of a Conditional Test Only some statements are executed
day == "Monday"
evening_plan = "Watch HIMYM"
"Are they equal?" test
Yes
No
2012-04-30 Katherine Deibel, Fluency in Information Technology 8
True or False? All conditions result in either true or false The condition is usually a test
Example: day == "Monday" Conditions can also be a Boolean value
Suppose leap_year is a Boolean variable:if(leap_year)
Feb_days = 29; Which is equivalent to:
if(leap_year == true)Feb_days = 29;
2012-04-30 Katherine Deibel, Fluency in Information Technology 9
If-Then-Else Branch both ways with If-Then-Else:
if(<Boolean expression>) <Then statement>;else
<Else Statement>; In JavaScript:
if(leapYear)daysInFeb = 29;
elsedaysInFeb = 28;
2012-04-30 Katherine Deibel, Fluency in Information Technology 10
If-Then-Else
if(leapYear)
daysInFeb = 28
True False
daysInFeb = 29
2012-04-30 Katherine Deibel, Fluency in Information Technology 11
If-Else If- Else
if(month == "January")days = 31;else if (month == "February")days = 28;else if (month == "March")days = 31;…else if (month == "December")days = 31;
2012-04-30 Katherine Deibel, Fluency in Information Technology 12
A Slight Diversion:Some JS FunctionsAlert, Confirm, Random
2012-04-30 Katherine Deibel, Fluency in Information Technology 13
Functions (in programming) Functions are not like math functions Functions are subroutines
One or more statements separate from the main program
Functions are called by the main program or other functions
Functions simplify writing code by allowing coders to reuse complex statements without copying/pasting
2012-04-30 Katherine Deibel, Fluency in Information Technology 14
JS Function: Math.random() Returns a random decimal number x
from the range 0≤x<1 Usage:
var x = Math.random();
2012-04-30 Katherine Deibel, Fluency in Information Technology 15
JS Function: alert("…") Generates a message box with an OK
button Message box displays the message string
that is alert's parameter Example:
alert("Let's show off the alert() function");
2012-04-30 Katherine Deibel, Fluency in Information Technology 16
JS function: confirm("…") The operation confirm() is like alert()
except it has two buttons: Cancel and OK When the user clicks a button, the system
returns to the program the information of which button was clicked: Cancel 0 OK 1
We can illustrate this behavior
2012-04-30 Katherine Deibel, Fluency in Information Technology 17
Demo: confirm()
2012-04-30 Katherine Deibel, Fluency in Information Technology 18
<html xmlns="http;//www.w3.org/1999/xhtml" xml:lang="en"> <head> <title>First JavaScript</title> <style type="text/css"> body {background-color: black; color: gold; font-family; corbel;} </style> </head> <body> <h1>Showing Simple JS</h1> <script type="text/javascript"> var whatButton;
whatButton = confirm("Do you bring your clicker to class every lecture?");
if(whatButton == 1) alert("You clicked OK");
elsealert("You clicked Cancel");
</script></body></html>
Demo: confirm()
2012-04-30 Katherine Deibel, Fluency in Information Technology 19
Doing More Work With if and if-else statements, only the
immediate statement after the if and the else are executed:
if(temp < 32)water = "ice";state = "frozen"; always executed
To do more stuff, we could test againif(temp < 32)
water = "ice";if(temp < 32)
state = "frozen";2012-04-30 Katherine Deibel, Fluency in Information Technology 20
Compound Statements A better solution: compound statement Any number of statements enclosed in curly
braces { }, is treated as one statement Example:
if(temp < 32){
water = "ice";state = "frozen";
}No semicolon after the brace!!
2012-04-30 Katherine Deibel, Fluency in Information Technology 21
If within an If
if(clean_clothes > 0)if(day=="Saturday")
morning_plan = "Sleep In";else
morning_plan = "Do_Laundry";
2012-04-30 Katherine Deibel, Fluency in Information Technology 22
If there are no clean clothes …?
If within an If: Caution
if(clean_clothes > 0)if(day=="Saturday")
morning_plan = "Sleep In";else
morning_plan = "Do_Laundry";
Else always associates with the nearest if.Indentation does not matter!
2012-04-30 Katherine Deibel, Fluency in Information Technology 23
How JS Interprets the Code
if(clean_clothes > 0)if(day=="Saturday")
morning_plan = "Sleep In";else
morning_plan = "Do_Laundry";
Put nested ifs in compound statements
2012-04-30 Katherine Deibel, Fluency in Information Technology 24
The Better Code
if(clean_clothes > 0) {if(day=="Saturday") {
morning_plan = "Sleep In";}
}else {
morning_plan = "Do_Laundry";}2012-04-30 Katherine Deibel, Fluency in Information Technology 25
Recommended Practice Always use curly braces with if and if-
else statements Most of the time, you will be doing it
anyhow Easier to add more statements later
2012-04-30 Katherine Deibel, Fluency in Information Technology 26
Relational & Logic OperatorsPaging Dr. Ruth or Dr. Spock…
2012-04-30 Katherine Deibel, Fluency in Information Technology 27
Relational Operators Make comparisons between numeric values Used in if statements and for stop tests in
loops (later topic) Outcome is a Boolean value, true or false
< less than<= less than or equal to== equal to!= not equal to>= greater than or equal to> greater than
2012-04-30 Katherine Deibel, Fluency in Information Technology 28
= versus == = is the assignment operator == is the test for equivalence Never use = in an if-statement!
It will usually always default to true.
2012-04-30 Katherine Deibel, Fluency in Information Technology 29
Logic Operators Allow you to combine multiple tests
x && y both x AND y must be truex || y either x OR y must be true
Good practice to put each test in parentheses
Example:if(leapYear && (month == "February"))
days = 29;
2012-04-30 Katherine Deibel, Fluency in Information Technology 30
Comparing Strings You can use relational operators with
strings as well "Alice" < "Bob" true "Alice" == "Bob" false "Alice" >= "Bob" false "Alice" == "Alice" "Alice" == "alice" "Alice" >= "Alice"
2012-04-30 Katherine Deibel, Fluency in Information Technology 31
truefalsetrue
Summary Conditional statements allow us to
execute some statements and not others The test is enclosed in parentheses We always use compound statements to
group the operations of conditional statements properly
A compound statement is just a bunch of statements inside of { } … DO NOT follow it with a ;
2012-04-30 Katherine Deibel, Fluency in Information Technology 32
top related