1 / 18

JavaScript: Comparisons and Conditionals

JavaScript: Comparisons and Conditionals. Comparing for equality Logical And/Or. Learning Objectives. By the end of this lecture, you should be able to: Describe the difference between the assignment operator = and the equality operator ==

pbaker
Download Presentation

JavaScript: Comparisons and Conditionals

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. JavaScript: Comparisons and Conditionals Comparing for equality Logical And/Or

  2. Learning Objectives By the end of this lecture, you should be able to: • Describe the difference between the assignment operator = and the equality operator == • Describe the use and application of the logical ‘OR’ operator: || • Describe the use and application of the logical ‘AND” operator: &&

  3. Relational operators Relational operators allow us to test the relationship between two items. Often this involves numbers (e.g. age>=65), but we also may want to compare, say, two Strings. For example, we may want to check if a user’s password matches the password on file. Here are some relational operators: Inequality >, >=, <, <= Not equal != Equal == We haven’t discussed these last two yet… 3

  4. Comparing for ‘equality’ We’ve seen many code examples comparing items for greater than or less than. What about comparing two items to see if they are the same? Example: Prompt the user for the day of the week. If it’s a Sunday, our program should print: “No need to pay the meter!” var day; day = document.getElementById('txtDay').value; //Note: No ‘parse’ here since ‘day’ is not a quantity! if (day == "Sunday") //checking for equality { alert("No need to pay the meter!"); } Note the comparison operator ‘ == ‘ . If you want to compare two values, you need to use ‘==‘. Using one equals sign ‘=‘ will NOT work!

  5. ‘=‘ vs ‘==‘ Don’t confuse these! The equals symbol ‘=‘ is the operator that is used to assign some value to a variable. For example: var age = 34; //this is an assignment If we want to compare values, we must not use the ‘=‘ operator because, again, the equals operator assigns a value to a variable. That is, the ‘=‘ operator does not compare! If we want to compare, we use the (very similar) operator: ‘==‘ • if (name == “Bob”) …. • if (age == 65) …. • if (birthday == todayDate) ….

  6. So, don’t forget… The point to remember is that whenever you are trying to compare a variable to a value to see if they are identical, you should check carefully check to make sure that your conditionals use only the equality operator: == Typing = (a single equals sign) instead of == is pretty much guaranteed to result in a bug in your program. In a lengthy and/or complex program, this error can sometimes be quite difficult to track down! 6

  7. if (day == "Sunday")Why did we need quotes? var day = document.getElementById('txtDay').value; if (day == "Sunday") { alert("No need to pay the meter!"); } Supposing we had instead written: if (day == Sunday) Can you spot the problem? In this case, JavaScript would think that Sunday was a variable. By placing the word “Sunday” inside quotes, we are telling JavaScript that we are comparing the variable called day with a String (“Sunday”).

  8. Example If the day is a Sunday, tell them they don’t have to feed the meter. If it is not Sunday, say: “Better get some quarters!” var day = document.getElementById('txtDay').value; if (day == "Sunday") { alert("No need to pay the meter!"); } else { alert("Better get some quarters!"); } Notes: • Remember that it’s perfectly okay to declare a variable and assign it a value on the same line. • It’s okay to have the opening brace of a block on the line that precedes the block. • The closing brace should always be on its own line.

  9. Can your user spell? • A top-notch programmer will go out of their way to make sure that their program will work regardless of the unpredictable things that a visitor to your page might try to do. • This can occupy lots of time and code, but it is extremely important. • As a relatively simple example: Suppose that in our parking-meter example, a user types ‘sunday’ (i.e. they do not capitalize the ‘s’)? var day = document.getElementById('txtDay').value; // Suppose the user typed ‘sunday’ (i.e. lower case ‘s’) if (day == "Sunday") // Will be FALSE • Answer: the logical expression would evaluate to false since “sunday” does NOT equal “Sunday”.

  10. Handling unexpected input • Let’s re-write our logical expression so that if the user enters “sunday” OR “Sunday” the expression will hold true regardless. if (day == "Sunday" OR day == "sunday") … • The word “OR” is not part of JavaScript. However, there IS a way of representing it: || • The | (usually found above enter on your keyboard) is called the “pipe” character. Putting two pipes together (no space) is known as a “logical or”. When you have two or more conditionals separated by the “logical or” || , what needs to happen in order for the logical expression as a whole to evaluate to true? • Answer: If *ANY* of the conditionals is true, the entire logical expression will evaluate to true. if (day == "Sunday" || day == "sunday") • If ANY of the above conditionals is true, the entire logical expression will be true • Incidentally, you don’t need all the extra spaces. (In fact, they should not be there – one space is enough!) I just put them in there for teaching purposes.

  11. Multiple Conditionals Separated By Logical ORs Example: if (day=="Sunday" || day=="sunday" || day=="Domingo" || day=="Vendredi" || day=="Sondag") Under what circumstances will this logical expression evaluate to True? Answer: It is perfectly acceptable – in fact, fairly common – to have multiple conditionals inside a logical expression. In the above example, because all of the conditionals are separated by logical ORs, as long as ONE of the above conditionals is true, the entire logical expression will evaluate as true.

  12. Parking meter example -- slightly improved version: If the user says that today is Sunday – with upper-case or lower case ‘s’, tell them they don’t have to feed the meter. If it is not Sunday, say: “Better get some quarters!” var day = document.getElementById('txtDay').value; if (day=="Sunday" || day=="sunday" ) { alert("No need to pay the meter!"); } else { alert("Better get some quarters!"); }

  13. BUG ALERT! One very common error made by new programmers is forgetting to repeat the variable in each conditional: var day = document.getElementById('txtDay').value; if (day == "Sunday" || "sunday" ) { alert("No need to pay the meter!"); } The above example will cause the page to fail to work. Note that the variable must be repeated for every conditional: var day = document.getElementById('txtDay').value; if (day == "Sunday" || day == "sunday" )

  14. Multiple Conditionals Separated By Logical ANDs (&&) Also very common are situations in which two or more conditionals must ALL be True: For example, suppose that in order to be allowed to vote, an individual must 1) be registered, and 2) be at least 18 years old. In other words, ALL requirements must be met. The syntax follows: if ( age >= 18 && registered=="yes") { alert("You may vote") } else { alert("You may not vote"); } • As with OR statements, you can have as many conditionals as you need inside the logical expression. Summary: When separated by logical AND (i.e. && ), the rule is that ALL conditionals must be true in order for the logical expression to evaluate to true.

  15. Multiple Conditionals are Perfectly Acceptable You can have as many conditionals as you like inside the logical expression. if (age >= 18 &&registered=="yes" &&citizen=="yes" &&notFelon=="yes") { alert("You may vote") } else { alert("You may not vote"); } Also, recall that when multiple conditionals are separated by the logical and operator, &&, all of the conditionals must be True for the whole logical expression to evaluate to True.

  16. Using braces for ‘if’ statements If your ‘if’ statement has only one line of code, the braces are optional. if (logical expression) { statement 1 statement 2 } if (logical expression) statement In general, I recommend that you ALWAYS use braces – even in those cases where your block is only one statement long. Only once you get very comfortable, should you use this shortcut. more than one statement – braces are required one statement only – braces are optional 16

  17. <body> <h2>Vote Checker</h2> <form id="voterInfo" class="form-style-classic"> <p>How old are you? <input type="text" id="txtAge" size="10"></p> <p>Are you registered to vote? (Enter 'yes' or 'no'): <input type="text" id="txtRegistered" size="8"></p> <p>Are you a convicted felon?< (Enter 'yes' or 'no'): <input type="text" id="txtFelon" size="8"></p> <p>*** <button type="button" onclick="checkVoterEligibility()" style="background-color:#ffff99;"> Can I Vote?</button> ***</p> </form> <script> function checkVoterEligibility() { var age, isFelon, isRegistered; age = document.getElementById('txtAge').value; age = parseInt(age); isRegistered = document.getElementById('txtRegistered').value; isFelon = document.getElementById('txtFelon').value; if ( age>=18 && isRegistered=="yes" && isFelon=="no") { alert("Congratulations, you may vote!"); } else { alert("I'm sorry, you are not qualified to vote."); } } </script> </body> vote_check.html (partial)

  18. File: vote_check.html Be sure to study the vote_check.html file. Other elements are included there including a review of classes, a div section for outputting, and other things. Remember that studying existing code is one of the best ways to learn and review coding skills.

More Related