460 likes | 611 Views
Operators and Statements. Assignment Statements Mathematical Operators Conditional Logic if and switch statements Ask a question (test a condition) Do something based on truth Has the kettle boiled? The pour water into cup. Else wait. Assignment Statements. mySalary = 1200.16;
E N D
Operators and Statements • Assignment Statements • Mathematical Operators • Conditional Logic • if and switch statements • Ask a question (test a condition) • Do something based on truth • Has the kettle boiled? The pour water into cup.Else wait
Assignment Statements • mySalary = 1200.16; • mySalary = mySalary+ 100; • myFName = "Steve" ; myLName = "Perry"; • myAge = getMyAge("StevePerry");
Numerical Calculations • Basic mathematical operators • +, -, *, / • Example: • Assigning the value of a calculation: • var TotalCostOfShopping; TotalCostOfShopping = 10 + 5 + 5;alert(TotalCostOfShopping); • 10 + 5 + 5 is referred to as an “expression”
Exercise 2.1 • Write a web page that displays the circumference of circle whose radius is .67 inches. The formula to calculate the circumference of circle is 2PIr, where PI = 3.1459 and r is the radius
Increment/Decrement( Unary Operators ) • myVariable = myVariable + 1;myVariable = myVariable - 1; • Or use shortcut... myVariable++;myVariable--;
Another Shortcut • myVar += 6; //add 6 to myVar • Same as: myVar = myVar + 6;
Operator Precedence • USE PARENTHESIS!! • Multiplication and division first • then addition and substraction • left to right
Comparison Operators • What we use to make comparisons:= = ( Different than = )<><=>=!= Not Equals
Precedence • USE PARENTHESES ! • = = and != lowest order • <, >, <=, >= equal precedence • Instead of:3 * 5 > 2 * 5use:(3 * 5) > (2 * 5)
The if Statement • Makes the decision • e.gif (roomTemperature > 80){ roomTemperature = roomTemperature - 10;} • No semi-colon!
Block of Code • Code placed between curly braces { } is called a "Block" of code • In the last if statement, the entire block of code is executed if the condition evaluates to true (e.g. is the room temperature greater than 80 degrees?) • You can leave off { } for a single line, but don't!
Example • if (roomTemperature > 80){ roomTemperature = roomTemperature -10; alert("It's hot in here"); alert("Air conditioner switched on");}
Demo - Simple IF Statement Pause this slide and click the link below for a… video demonstration
Common Mistake • Be careful not to use a single = where you need = = • What happens with the following code? • degCent = 77;if (degCent = 100) { document.write("That's boiling"); alert("Centigrade is " + degCent);}alert("Finished");
Demo – Common Mistake Pause this slide and click the link below for a… video demonstration
Logical Operators • How do we ask the question, "Is the temperature greater than 32 and less than 211? • Logical Operators: • AND && • OR | | • NOT !
AND • With AND both sides of the condition must be true for the statement to be true • Example: • if (degCent > 0 && degCent < 100) do something...
OR • Only one side of the condition must be true for the the entire statement to be true • Example: • if (degCent < 0 | | degCent > 100) do something...
NOT • You can check if something is not true • Example: • if (!degCent == 0)
Never Mix NOTs and ORs! • if(city != "Boston" OR city != "Denver") do something… • What happens here?
A Tale of Two Cities • if(city != "Boston" || city != "Denver") do something… • If the city is Denver, it will not be Boston • If the city is Boston, it will not be Denver • If the city is Los Angeles, it will not be either Boston or Denver! • This statement is ALWAYS true
Nested if Statements • You can nest one if statement inside anotherif (degCent < 100) { if (degCent > 0) { document.write("degCent is…"); }}
else and else if • When the 'if' expression evaluates to true the code block found directly below the 'if' statement is executed • When the expression evaluates to false, then you use the 'else' clause to execute the code block under it
Examples • if (myAge >= 0 && myAge <= 10){ document.write("myAge is between 0 and 10");}else{ document.write("myAge is NOT between 0 and 10");}
Exercise 2.2 • Use a nested if-statement in the following: • Write a program to prompt a user for their name and eye color • If their name is 'Steve', display • "You are the Instructor" • Otherwise display "Hi <name>" • If their eye color is blue, display • "Hi, blue eyes" • Otherwise display "You have <color> eyes";
else if • if (myAge >= 0 && myAge <= 10) { document.write("myAge is between 0 and 10");}else if ( myAge >= 30 ) { document.write("myAge is over 30");}else{ document.write("myAge is between 10 and 30");}
Comparing Strings • var myName = "Paul";if (myName = = "Paul") { alert("myName is Paul");} • Comparisons ARE case-sensitive • lowercase letters are greater than uppercase! • use toUpperCase( ) or toLowerCase( )
The switch Statement • Uses for checking the value of a particular variable for a large number of possible values • May be clearer then using “esleif”
Example • switch (myName){ case "Paul": //some code break; case "John": //some code break; default: //some code break;}
Elements of switch • Think of the statement as:"switch to the code where the case matches" • Breakdown: • text expression • case statements • break statements • default statements
Exercise 2.3 • Use the switch statement in a program that asks a user to enter a number between 1 and 100 • If the number entered is 1, 2, or 3 display "You're too low" • If the number entered is 4 display "That's It!" • If the number entered is 5 or greater display "You're too high"
Looping • Looping means to repeating blocks of code • You continue looping while a condition is true
The for Loop • for (cntr=1; cntr <=3; cntr++){ // execute some code} • Initialization, test condition, increment
How it works • Execute initialization • Check the test condition • if true, continue, if not exit the statement • Execute code in the code block • Execute the increment • Repeat 2 to 4 until the test condition is false
Exercise 2.4 • Write a program that will display the number of lines a user requests. • Display the line in the following format • "this is line number <iteration number>"
while Loop • The 'for' loop executes a certain number of times • The 'while' loop executes until a certain condition is met • Example: while (degCent != 100) { // some code }
Example • degCent = new Array( ); //New ArraydegFahren = new Array(34, 123, 212);var loopCounter = 0;while (loopCounter < 3){ degCent[loopCounter] = 5/9 * (degFahren[loopCounter] - 32); loopCounter++;}
Demo – Indenting Code Pause this slide and click the link below for a… video demonstration
The Infinite Loop • A loop that will never end • CNTL-ALT-DELETE is your friend • If a condition is never met, then the loop goes continues indefinitely
The break and continue Statements • break - exits the loop and continues the execution of code after the loop • continue - exits the loop and continues the execution of the code at the beginning of the loop (i.e. it performs the next iteration)
Exercise 2.5 • Code a JavaScript program that will continuously prompt a user for items on a shopping list. Immediately after the user makes his or her entry, display the item on the window as a list item. • When the user enters "done", then exit the loop and display "End of list"
Spot the Infinite Loop! • var testVariable = 0;while (testVariable <=10){ alert("Test variable is " + testVariable); testVariable++; if (testVariable = 10) { alert("The last loop"); }}
The do…while Loop • Executes code inside the loop and then checks the condition • Insures that the code inside the loop is executed at least once • Examplevar userAge; do { userAge = prompt("Enter your age",""); } while (isNaN(userAge) = = true)
Exercise 2.6 • Write while-loop that prompts the user to enter their age. • If their age is over 18, prompt them for their name and display "You may enter the club <name>" on the browser window. • If they are under 18, display. You may not enter the club and re-prompt the user for their age.