No.7 Conditional Statements

Inputting Data

Humans operate a computer by using a mouse or keyboard.  This is called “Input”. On the other hand, a computer communicates with humans by displaying texts and images, or making sounds from speakers.  This is called “Output”. We will learn about the relationship of the structure of computers and input/output on the 10th lesson.

Inputting Strings

Up to now, we have used mouse click as an input. Now, let’s try using the keyboard for input.  Make a textbox (as we learned on the 2nd lesson)、and JavaScript will be able to read the input.

Exercise 07-1(☆)
  1. Create ex07-1.html and fill in the following. Note that the text input element/tag is now “wrapped” with paragraph  tag (<p> tag). In this case it’s done so the text “Who?” can be displayed next to the text box.
  2. Create ex07-1.js and fill in the following.
  3. Type in your name in the textbox and click the button.

In order to read the value entered by the user, we use document.getElementById().value.  Note that it is different from document.getElementById().innerHTML, which we learned in the previous lesson. Also note that it is an event on the button (onclick) that calls the function to read the value. Do you remember “onchange” event (Exercise 05-13)? How would you use this for this case? You can eliminate the  need of having to click a button like the above for the purpose of reading a textbox! Read it here onchange event and text box

innerHTML
The content of the HTML element (tags excluded).”whatever in between the tags”
value
In case of textbox, it means the data input typed by the user. Other input elements such as buttons and checkboxes has value attributes but they are slightly different.
Exercise 07-2(☆☆☆)

In the exercise above, make another textbox that would allow you to enter a word so that the first word (“Hello”) can be changed to whatever the you have entered in that text box . For instance when “Yo” is entered in this textbox and “Taro” is entered in the “Who?” textbox, the result displayed when clicking the button should be “Yo, Taro!”. These 2 are Strings. Remember the operation to concatenate two Strings (Exercise 05-10) is “+”. The same operator (“+”) will add two Numbers.

Entering Numeric Values

Review Data Types (Lesson 5, point 5.4) to refresh your memory about the difference of String data type and Number data type.

As mentioned above anything entered in a text box is treated as a String, whether it is alphabetical (a,b,c..) , numerical (0,1,2), or anything else. This means  numbers entered in a textbox is handled as a String data type.  When we want to calculate these numbers, we must use Number() (which we learned in the 5th lesson) and convert them into Number data type before you can treat them as numbers.

Exercise 07-3(☆☆)Making a “simple calculator” to add two numbers
  1. Create ex07-3.html and fill in the following.
  2. Create ex07-3.js and fill in the following.
  3. Fill in a random number in the text box and click the calculate button. You will see that it is not working as expected as a calculator (to do the sum)
  4. Fix the program. The String needs to be converted to Number (Exercise 05-10)
Exercise 07-4(☆☆☆☆)

Make a program that calculates your BMI when you enter your height and weight.

if Statements and Conditional Expressions

How to write an if Statement

In general, programs are executed in order from the top  to the bottom , but there is a method to write multiple instructions and execute the ones that only matches in particular situations. This is called a conditional expression, and in JavaScript the “if statement” is used.

Exercise 07-5(☆)
  1. Create ex07-5.html and fill in the following.
  2. Create ex7-7-05.js and fill in the following (note that there are two equal marks next to each other, == instead of =).
  3. Type in the correct answer and click the button.  Try entering a wrong answer as well.

There are two constructs of if statement.

  1. Execute the command when the condition is true, and do nothing when false. The example for this is Exercise 07-5 above.
    ifblock
  2. Execute a command when the condition is true, and execute another when false.
    ifelseblock

The two constructs are:

  1. if ( condition ) { process }
  2. if ( condition ) { process1 } else { process2 }
Exercise 07-6(☆☆)

Edit the previous file so the message “Wrong!” appears when the answer is incorrect. This requires you to rewrite the program in #2 style above, assigning “process2” for displaying “Wrong”.

Specifying Conditions for If statement

All conditions specified in an If statement are evaluated to either “true” or “false”, as you can see in the flowchart/diagram above. There are ways to specify these conditions. For the purpose of specifying the Condition in an If statement, let’s review the followings:
Relational Operations, Complex Comparison, Logical Operator. They will be explained in the following sections. A valid Condition for If should be a statement that result in “true” or “false”. You will see what are these “true” and “false” when you do exercise below (executing/typing condition/statement in console).

Relational Operators

In a program, numerical equality and inequalities are handled as operators as well as + - * /.  In order to operate a  numerical equality and inequality, we use operators such as “<“, “!=” or ” ==”.

By writing a relational operators between two expressions, the program compares them and gives you the result. The result is a Boolean data type and it is either true or false. Example:

if ( x>3 ) { alert('bigger') }

Exercise 07-7(☆☆)
  1. Execute the following with console to find out how those operator works
    • var x=2
    • x==2
    • x==3
    • x!=2
    • x!=3
    • x<2
    • x<=2
    • x<=3
    • '2'==2
    • '2'===2
  2. Edit Exercise07-6 and change the conditional statement from “equal” (==) to “not equal”(!=), and replace “Correct” and “Wrong ” accordingly to keep the program works correctly.

The reason why we use two equal marks is because one single equal mark is the command that assigns a value to a variable. It will not get evaluated to true or false, hence not suitable to be used as a Condition in If statement. If you mistakenly enter only one equal mark inside the condition, no errors will occur but the program will most likely give you the wrong result.

Exercise 07-8(☆☆☆)
  1. Fix the change you made in No.2 of Exercise 07-7 back.
  2. Erase one equal mark inside the conditional statement.
  3. Type in a wrong answer in the textbox and solve the riddle.
  4. What happended and why?
  5. Fix the program back.

Complex Comparisons

Let’s make the answer newspapers correct as well (not only “newspaper”).

In order to do so, we must compare the input, “newspaper”, and “newspapers”.  However, a relational operator can only compare two values at once.  Let’s try comparing the three by combining two if statements, comparing it in 2 stages: compare it to “newspaper” first , then compare it to “newspapers” later. This means you need to have 2 conditionals. Let’s implement it below.

Exercise 07-9(☆☆☆)
  1. Draw the following image on a paper.  Write “If the input equals ‘newspaper’ ” for “Condition”, and write “display ‘correct’ “for “Process 1”.
    ifelseblock
  2. Now to check for “newspapers“-with s, you need to place another Condition check /Decision inside “Process 2”. Basically you would substitute Process 2 with another Decision/Condition check. It’s like having a whole flowchart above inside Process 2 (nested). For this second  Decision, what should you write inside Condition, and the 2 processes under the Condition? Check out this Flowchart as an illustration only for this case Sample flowchart (source:1.bp.blogspot.com)
  3. Edit the riddle program to match the diagram
    • It is troublesome having to write document.getElementById('answer').value each time, so you should assign a value to a variable first, and use the variable later, for example var theanswer=document.getElementById('answer').value
    • When the input does not match ‘newspaper’, another if statement should be used to compare the input and ‘newspapers’.

If there is only one statement inside the true/false part of an if statement, the { } can be taken off (actually, you can only write one statement, so we use { } to have two statements). It is however a good practice to always use { } even if you only have one statement.

Sometimes you see another single if statement that comes after an else. This is an  else if structure and the format is the as described below.

For this structure the condition1 is first checked. If condition1 is true then the process1 get executed. Else If condition1 is false then condition2 get checked.  If condition2 is true then process2 get executed. Else If condition2 is false the condition3 get checked and so on. If all the conditions are false then process_n (under else) get executed. Flow chart of the else if structure: (source:www.codewithc.com)

    if (condition1) {
       process1
    } else if (condition2) {
       process2
    } else if (condition3) {
       process3
    } .....
       .....
    } else {
       process_n
    }
Exercise 07-10(☆☆☆☆)

Edit the program from Exercise  07-4 so that the following messages show up. Use the else if structure explained above.

  1. When the BMI is under 18.5, “Underweight
  2. When the BMI is over 25, “Overweight
  3. When the BMI is in between, “Normal
  • The first if statement should check the condition whether the BMI is under 18.5.
  • If the BMI is over 18.5, the second should check the condition whether its under 25.

Logical Operators

Another method when doing multiple comparison of values is using logical operators. The result is called “boolean” and it is either true or false. There are 3 basic logical operators: AND, OR, and NOT. Their “truth tables” are provided below.(source: wikimedia.org)

The following logical operators are used in JavaScript: && for AND, || for OR, ! for NOT. Examples:

  1. (x&&y) means (x AND y)
  2. (x || y) means (x OR y)
  3. !x means NOT x

x and y can represent Conditions for If statement. for example x is (a<5), y is (a>1), or for example x is (b==”newspaper”) y is (b==”newspapers)-just like in the exercise 07-9.

Examples

  1.  ( (a<5) && (a>1) ) . This is true for a with values of 2,3,4
  2. ( (b==”newspaper) || (b==”newspapers) ) This is true for a with value of “newspaper” and also true for b value of “newspapers”
  3. !(a<5). This is true for a values of 5,6,7,……
  4. ( (a>1) && (b<9) && (a!=5 ) ) . This is true for a with values of 2,3,4,6,7,8. Note here that there are 3 conditions!

Example of usage in if statement:

if ( (x>3)&&(x<10) ) { alert(‘size is OK’) }

Review the Reference below.

This method is based on logic. Logic is the basics of many subjects. For reference only , review these slides. (Download PPT)

 

Exercise 07-11(☆☆)

  1. Write a conditional expression of the following.
    • is larger than 1 and smaller than 10
    • is equal to either ‘newspaper’ or ‘newspapers’.
  2. Fix the riddle program so that only one if statement is used.

Exercise 07-12(☆☆☆☆☆)

Look at the Reference below and make a program that determines if it is a leap year or not by filling in a year in the textbox.

Points to Check
  • What is the difference between document.getElementById().innerHTML and document.getElementById().value?
  • What two methods are there when writing a if statement?
  • Which operator is used to determine whether two values are equal?
  • What data type is returned from a relational operator?
  • How can we compare three values at once?