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

Slides:



Advertisements
Similar presentations
Making Decisions in Python Sec 9-10 Web Design. Objectives The student will: Understand how to make a decision in Python Understand the structure of an.
Advertisements

Python Programming Language
CIS101 Introduction to Computing Week 11. Agenda Your questions Copy and Paste Assignment Practice Test JavaScript: Functions and Selection Lesson 06,
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
Programming Fundamentals. Today’s lecture Decisions If else …… Switch Conditional Operators Logical Operators.
Conditional Execution
Agenda Basic Logic Purpose if statement if / else statement
Lecture 2 Conditional Statement. chcslonline.org Conditional Statements in PHP Conditional Statements are used for decision making. Different actions.
Decision Making and Branching
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
© 2010 Robert K. Moniot1 Chapter 6 Introduction to JavaScript.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this.
JavaScript – If/Else contd
JavaScript: Conditionals contd.
BIT116: Scripting Lecture 05
Precedence Operators Error Types
Introduction to Decision Structures and Boolean Variables
If/Else Statements.
Moving away from alert() Using innerHTML Using an empty div section
Chapter 10 Programming Fundamentals with JavaScript
CHAPTER 10 JAVA SCRIPT.
Concatenation Comments
Python: Control Structures
Programming Mehdi Bukhari.
Debugging and Random Numbers
Operator Precedence Operators Precedence Parentheses () unary
Retrieving information from forms
The order in which statements are executed is called the flow of control. Most of the time, a running program starts at the first programming statement,
Simple Control Structures
Lecture 3 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz
Chapter 6: Conditional Statements and Loops
Lesson 9: "if-else-if" and Conditional Logic
CHAPTER 4 CLIENT SIDE SCRIPTING PART 2 OF 3
Control Structures.
Chapter 10 Programming Fundamentals with JavaScript
Conditionals & Boolean Expressions
Lesson 8: Boolean Expressions and "if" Statements
Conditional Statements
Learning to Program in Python
Conditions and Ifs BIS1523 – Lecture 8.
Scratch: selection / branching/ if / If…else / compound conditionals / error trapping by Mr. Clausen.
Repetition Structures
Coding Concepts (Sub- Programs)
During the last lecture we had a discussion on Data Types, Variables & Operators
T. Jumana Abu Shmais – AOU - Riyadh
Java Programming Control Structures Part 1
If selection construct
Selection Statements.
Computing Fundamentals
Conditional Execution
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Python Programming Language
Programming with Alice
Chapter 3: Selection Structures: Making Decisions
Boolean Expressions to Make Comparisons
Week 3 – Program Control Structure
'Boolean' data type.
An Introduction to Linux
Chapter 4: Boolean Expressions, Making Decisions, and Disk Input and Output Prof. Salim Arfaoui.
BIT116: Scripting Lecture 6 Part 1
CHAPTER 5: Control Flow Tools (if statement)
Chapter 3: Selection Structures: Making Decisions
Javascript Chapter 19 and 20 5/3/2019.
Module 3 Selection Structures 6/25/2019 CSE 1321 Module 3.
Computers and Scientific Thinking David Reed, Creighton University
Switch Case Structures
JavaScript Part 2 Organizing JavaScript Code into Functions
Retrieving information from forms
Presentation transcript:

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

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.

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

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

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

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

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

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

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

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

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!");

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!");

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

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!"); }

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

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 =.

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

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!"); }

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.");

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)…

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.