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

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

karlyn-bohler
karlyn-bohler . @karlyn-bohler
Follow
343 views
Uploaded On 2020-01-17

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

JavaScript Controlling the flow of your programs with if statements if something is true Do this stuff here else Do this other stuff Learning Objectives By the end of this lecture you should be able to ID: 773022

conditional block statements age block conditional age statements hours code alert user

Share:

Link:

Embed:

Download Presentation from below link

Download Presentation The PPT/PDF document "JavaScript Controlling the flow of your..." is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.


Presentation Transcript

JavaScript Controlling the flow of your programs with ‘if’ statements if (something is true) { Do this stuff here } else { Do this other stuff }

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 order (a.k.a. “flow”) of JavaScript commands is executed based on whether or not a conditional evaluates to trueWrite simple scripts demonstrating comfort with if and if-else statementsInterpret – and write – slightly more involved web page using if-else statements such as the one demonstrated in salary_calculator.html

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 the particular situation. 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.

4 Other hypothetical scenarios If the due date of a book is before today’s date Charge an overdue fee to the member If the number of hours worked is more than 40 Add overtime pay to the person’s salary this week

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) Something in the code called a “conditional” is present. This conditional 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 conditional is false skip that block of code.

6 Syntax: The if statement 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 will be executed.However, if the ‘if’ condition is true, then once that “true” block has been executed, the else block will be skipped. NOTE: There is NO semicolon placed at the end of a conditional.

7 Blocks can be as long/short as you like if (conditional) { Block A statements Block A statements Block A statements Block A statements Block A statements Block A statements Block A statements 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.

8 An else block is not required if (conditional) { Block A statements Block A statements Block A statements Block A statements Block A statements Block A statements Block A statements 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. We will see examples of this.

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 statements}

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"); //We would use innerHTML in the “real world” } else { alert("Your ticket costs $10.00"); } Complete file: movie_ticket_simple.html

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 = parseFloat(hours); //people might enter decimals here! if (hours > 40) { alert("You qualify for overtime pay!"); } alert("Goodbye!");

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 = parseFloat(hours); if (hours > 40) { alert("You qualify for overtime pay!"); } alert("Goodbye!"); }

13 Summary: The if-else statement 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 the “if” block Should an ‘else’ block be present, it will be executed – but ONLY when the “if” conditional was false Again, do not forget that an ‘else’ block is optional . Whether or not you decide to include one depends on the business logic of your page.

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. Take a moment to try and write the relevant code your own before looking at my version. Start with a version that does not have an else block. Simply output “You can rent a car” if the user is 18 or over. Assume the text field is called “txtAge”. You can use alert() to keep things simple for the exercise.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: Take a moment to try and write the relevant code your own before looking at my version. This time, DO include an else block. Output “ You can rent a car ” if the user is 18 or over. Output “ Sorry, junior ” if the user is not yet 18. Assume the text field is called “ txtAge ”. var age; age = document.getElementById('txtAge').value; age = parseInt(age); if (age >= 18) { alert("You can rent a car!"); } else { alert("Sorry, junior");}

The >= operator This is a way of saying “equal or greater than”.In the last example, the conditional: age >= 18is 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 Exercise 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”. If they did not work over 50 hours, don’t say anything. Assume the text field is called “ txtHours ”. NOTE: Do NOT confuse ‘more than 50 hours’ with ‘50 or more hours’… One uses the ‘>’ operator, the other uses the ‘>=‘ operator. var hours; hours = document.getElementById('txtHours').value; hours = parseFloat(hours); if (hours > 50) { alert("Wow, you're a hard worker!"); }

18 Exercise Ask their age: If the user’s age is 65 or over, say “You are eligible for retirement benefits”, otherwise, say “Sorry, no benefits yet!” Assume the text field is called “ txtAge ”. Again, feel free to use alert() since we are just practicing. var age = document.getElementById('txtAge').value; age = parseInt(age); if (age >= 65) { alert("Eligible for retirement benefits"); } else { alert("Wait a few years, sorry."); }

The conditional: if (………) The conditional is the key component of ‘if’ statements. The conditional 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)…

File: salary_calculator.html 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 next if-else lecture will assume that you have a clear understanding of this material. 20