320 likes | 415 Views
INFO100 and CSE100. Fluency with Information Technology. JavaScript Logic Conditionals, Branches, Tests… Oh My!. Katherine Deibel. JavaScript So Far…. Plain text instructions for dynamic pages In <script type="text/ javascript ></script> tags Or in a separate file Variables
E N D
INFO100 and CSE100 Fluency with Information Technology JavaScript LogicConditionals, Branches, Tests… Oh My! Katherine Deibel Katherine Deibel, Fluency in Information Technology
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 Katherine Deibel, Fluency in Information Technology
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 laundry Else put on underwear Katherine Deibel, Fluency in Information Technology
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 Katherine Deibel, Fluency in Information Technology
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 Katherine Deibel, Fluency in Information Technology
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"; Katherine Deibel, Fluency in Information Technology
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"; Katherine Deibel, Fluency in Information Technology
Effects of a Conditional Test • Only some statements are executed "Are they equal?" test day == "Monday" Yes evening_plan= "Watch HIMYM" No Katherine Deibel, Fluency in Information Technology
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; Katherine Deibel, Fluency in Information Technology
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; Katherine Deibel, Fluency in Information Technology
If-Then-Else if(leapYear) True False daysInFeb = 29 daysInFeb = 28 Katherine Deibel, Fluency in Information Technology
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; Katherine Deibel, Fluency in Information Technology
A Slight Diversion:Some JS Functions Alert, Confirm, Random Katherine Deibel, Fluency in Information Technology
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 Katherine Deibel, Fluency in Information Technology
JS Function: Math.random() • Returns a random decimal number x from the range 0≤x<1 • Usage: var x = Math.random(); Katherine Deibel, Fluency in Information Technology
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"); Katherine Deibel, Fluency in Information Technology
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 Katherine Deibel, Fluency in Information Technology
Demo: confirm() <html xmlns="http;//www.w3.org/1999/xhtml" xml:lang="en"> <head> <title>FirstJavaScript</title> <style type="text/css"> body {background-color: black; color: gold; font-family; corbel;} </style> </head> <body> <h1>ShowingSimple JS</h1> <script type="text/javascript"> varwhatButton; whatButton= confirm("Do you bring your clicker to class every lecture?"); if(whatButton== 1) alert("You clicked OK"); else alert("You clicked Cancel"); </script> </body> </html> Katherine Deibel, Fluency in Information Technology
Demo: confirm() Katherine Deibel, Fluency in Information Technology
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 again if(temp < 32) water = "ice"; if(temp < 32) state = "frozen"; Katherine Deibel, Fluency in Information Technology
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!! Katherine Deibel, Fluency in Information Technology
If within an If if(clean_clothes > 0) if(day=="Saturday") morning_plan = "Sleep In"; else morning_plan = "Do_Laundry"; If there are no clean clothes …? Katherine Deibel, Fluency in Information Technology
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! Katherine Deibel, Fluency in Information Technology
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 Katherine Deibel, Fluency in Information Technology
The Better Code if(clean_clothes > 0) { if(day=="Saturday") { morning_plan = "Sleep In"; } } else { morning_plan = "Do_Laundry"; } Katherine Deibel, Fluency in Information Technology
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 Katherine Deibel, Fluency in Information Technology
Relational & Logic Operators Paging Dr. Ruth or Dr. Spock… Katherine Deibel, Fluency in Information Technology
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 Katherine Deibel, Fluency in Information Technology
= versus == • = is the assignment operator • == is the test for equivalence • Never use = in an if-statement! • It will usually always default to true. Katherine Deibel, Fluency in Information Technology
Logic Operators • Allow you to combine multiple testsx && 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; Katherine Deibel, Fluency in Information Technology
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" • true • false • true Katherine Deibel, Fluency in Information Technology
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 ; Katherine Deibel, Fluency in Information Technology