Presentation is loading. Please wait.

Presentation is loading. Please wait.

JavaScript Controlling the flow of your programs with ‘if’ statements

Similar presentations


Presentation on theme: "JavaScript Controlling the flow of your programs with ‘if’ statements"— Presentation transcript:

1 JavaScript Controlling the flow of your programs with ‘if’ statements

2 Learning Objectives By the end of this lecture, you should be able to:
Describe what is meant by a ‘conditional expression ‘ (a.k.a. boolean expression, a.k.a. logical expression) and how they are evaluated. Understand how the flow (order) of commands is executed based on whether or not a conditional evaluates to true. Write simple scripts demonstrating comfort with if and if-else statements. Interpret – and write – slightly more involved web page using if-else statements such as the one demonstrated in salary_calculator.htm.

3 Changing our code based on specific circumstances
At this point, all of our code always runs exactly the same way every time we submit our forms. Very, very often, however, we may want our code to react differently depending on just what the user entered. Here are some examples that we will learn to code. Each of these examples has a unique coding concept that we will learn to apply over the next couple of lectures: Suppose we want to create a page that determines the cost of a movie ticket. However, the cost of the ticket depends on the user’s age. The regular cost of a ticket is $10. However, if the user is 65 or over, the ticket cost should only be $5. Suppose we want to let a user know whether or not they are eligible to rent a car. In order to do that, they must be 18 or older, AND* must have a valid credit card. Suppose we want to let the user know whether or not they need to pay a parking meter. We ask the user for the day of the week. If it is a Sunday OR* a holiday, they do not have to feed the meter. Otherwise, they do. * The ‘AND’ and the ‘OR’ each have their particular coding constructs that we will learn about in subsequent lectures. 3

4 Other hypothetical scenarios
if due date on book is before today’s date Charge overdue fee if number of hours worked is more than 40 Add overtime pay 4

5 Conditional Execution
A conditional is something that evaluates to true or false. Unconditional execution (a conditional is not present) This is what we have been doing to date. All lines of the code are executed in sequence. Conditional execution (a conditional is present) A conditional is present, and is immediately followed by a certain block of code (which we put in braces). Here is how it works: First evaluate the conditional If the conditional is true, execute the block of code. If the condition is false skip that block of code. 5

6 Syntax: The if statement
NOTE: There is NO semicolon placed at the end of a conditional. if (conditional) { Block A statements… } else Block B statements… If the conditional inside the parentheses is true, the code inside the braces labeled ‘Block A’ will be executed. If the conditional is false, then the flow skips the block. In that case, the code inside the braces after the else statement. If the ‘if’ condition is true, then once that block has been executed, the else block will be skipped. 6

7 Blocks can be as long/short as you like
if (conditional) { Block A statements } else Block B statements The code inside these blocks can be as short (e.g. one line) or as long (e.g. 500 lines) as you wish. 7

8 An else block is not required
if (conditional) { Block A statements } Sometimes you have no need for an else block at all. This is absolutely fine. Whether or not you choose to include an else block depends on what your program is supposed to do. 8

9 Curly braces { } are called curly braces or simply braces.
Recall that we have already used these in the past: to delineate the beginning and end of our user-defined functions. As we have just seen, we also use braces to delineate the blocks that follow if and else statements. You should indent the code inside the braces for purposes of clarity. if (conditional) { statements } 9

10 Example – Movie Ticket Example: We retrieve the value from a form in which we ask the user their age. Our business requirements specify that a regular ticket costs $10, while a ticket for people 65 or over costs $5. var age; age = document.getElementById('txtAge').value; age = parseInt(age); if (age >= 65) { alert("Your ticket costs $5.00"); } else alert("Your ticket costs $10.00"); Complete file: movie_ticket_simple.htm

11 An ‘else’ is NOT required
'else' blocks are common – but they are not always needed. It is absolutely fine to have an ‘if’ without an ‘else’. If there is no 'else' block, the program still runs the same way. The only difference is that if the conditional evaluates to ‘false’, the flow will simply skip over the ‘if’ block and continue with the rest of the program. Again, this is nothing new. The program will simply jump over the ‘if’ block whenever the conditional is false. Example: Prompt the user for the number of hours they worked. If the hours are over 40, let them know that they will receive a bonus. If they do not qualify for a bonus, do not say anything. Try to write the relevant script out on your own before looking at the answer. var hours; hours = document.getElementById('txtHours').value; hours = parseInt(hours); if (hours > 40) { alert("You qualify for overtime pay!"); } alert("Goodbye!");

12 What happens after the if/else block?
Once an if/else block has completed, the program simply continues on through to the end of the function. In this example, regardless of whether or not the if block gets executed, the program will simply continue on and complete the rest of the function. In this case, the program will always alert “Goodbye”. function determineBonus() { var hours; hours = document.getElementById('txtHours').value; hours = parseInt(hours); if (hours > 40) alert("You qualify for overtime pay!"); } alert("Goodbye!");

13 Summary: The if-else statement
Conditional execution Evaluate the conditional following the ‘if’ Should that conditional evaluate to true, execute the block following the ‘if’ statement Should that conditional evaluate to false skip block following the ‘if’ statement If there is an ‘else’ block, execute that block only when the if conditional was false Again, note that the ‘else’ block is optional. Whether or not you decide to include one depends on the business logic of your page. 13

14 Another example Let’s write a script in which we ask the user for their age. If their age is 18 or over, print: “You can rent a car!” We will do it with and without an else block. Consider taking a moment to try and write the relevant code your own before looking at my version. Here is the version without an ‘else’ block: var age; age = document.getElementById('txtAge').value; age = parseInt(age); if (age >= 18) { alert("You can rent a car!"); }

15 Example that includes an ‘else’ block:
var age; age = document.getElementById('txtAge').value; age = parseInt(age); if (age >= 18) { alert("You can rent a car!"); } else alert("Sorry, junior"); 15

16 The >= operator This is a way of saying “equal or greater than”. In the last example, the conditional: age >= 18 is a way of saying: “if ‘age’ is equal or greater than 18” You can also use <= to indicate less than or equal to. Note: There is no space between > and =.

17 Practice – Solutions are on following slides
Ask the user how many hours they worked in the last week. If they worked more than 50 hours, output “Wow, you’re a hard worker”. NOTE: Do NOT confuse ‘more than 50 hours’ with ‘50 or more hours’… One uses the ‘>’ operator, the other uses the ‘>=‘ operator. Ask their age: If the user’s age is 65 or over, say “You are elegible for retirement benefits”, otherwise, say “Sorry, no benefits yet!” 17

18 If the user worked more than 50 hours, output “Wow, you’re a hard worker”.
var hours; hours = document.getElementById('txtHours').value; hours = parseInt(hours); if (hours > 50) { alert("Wow, you're a hard worker!"); }

19 Social Security Eligibility:
var age; age = document.getElementById('txtAge').value; age = parseInt(age); if ( age >= 65) { alert("Eligible for SS benefits"); } else alert("Wait a few years, sorry.");

20 The conditional: if (………)
The conditional is the key component of ‘if’ statements. The condtion asks a question that must ultimately be evaluated as either ‘true’ or ‘false’ is the user less than 21 years old? if( age < 21)… is the due date later than today’s date? if (dueDate > todayDate)…

21 File: salary_calculator
File: salary_calculator.htm This example is the level that you need to reach before moving on from this module. It may take some practice and review. Be sure to study this example until you completely understand it! The second if-else lecture will assume that you have a clear understanding of this material. There is also a slightly ‘cleaner’ version in which I removed the comments: salary_calculator_no_comments.htm However, in general, you should not be afraid to include comments throughout your code when you feel they can be helpful.


Download ppt "JavaScript Controlling the flow of your programs with ‘if’ statements"

Similar presentations


Ads by Google