Conditions

Goals


We aim to learn about conditional branching, which changes the program flow according to specific arguments or conditions. Conditional branching is one of the most basic elements in programming. We will also learn about alert() and prompt() as input/output interfaces to an elementary program, and explore Math.random () for generating a random number.

  • Using the prompt() function correctly and enter values ​​into variables.
  • Using the alert() function correctly, you can display messages while using variables.
  • It is possible to create a program using random numbers.
  • You can correctly write a single condition formula.
  • Multiple conditional expressions can be combined using logical operators.
  • Understanding the behavior of an if statement. You will learn to write if statements correctly.
  • Understanding the behavior of if-else statement. You can write if-else statements correctly.
  • Understanding the behavior of the else-if clause. You can write else-if clause correctly.
  • Understanding the behavior of switch statement. You can write switch statements correctly.

Using alert() and prompt()

In the program, it is common to gather input from the user and to issue messages in return. Here, we introduce prompt () and alert () which are the simplest methods of input and output using a browser and JavaScript.

prompt()


The prompt () function is a function that prompts input from the user through a popup window, and returns what the user entered as input to the JavaScript program.

The prompt() gives a pop up window with two elements: a message area which tells the user what to do, and an input area which lets the user type in an input. The prompt() function can put a single value in parentheses (Eg. “Enter one argument (or word)”) and display those values as a message. At the same time, the area for input is displayed, so users may enter a value in the text box provided. The value entered by the user is the value returned by the function.

Note: Since the value is returned as a character string here, caution is required when entering numbers.

In the following example, a popup for entering a value is displayed together with a message “What is your name?” The entered value is stored in the variable yourname.

...
var yourname = prompt("What is your name");
...

alert()

The alert() function is a function for displaying a message using a pop-up window. The alert() function takes one argument and displays its value in a popup as a message. An example of actual usage is shown below.

 

...
alert("Hello World!");
...

In this example, a character string represented by a string literal is simply displayed as a pop-up. On the other hand, you can write expressions in the parentheses of the alert() command. When you write an expression, the evaluated value is displayed as a popup.  

...
var yourname = "taro";
...
alert("Hello " + yourname);
...

 

Examples using prompt() and alert()

The following example is an example using prompt() and alert (). In this example, let’s enter a name on the first line and store the name you entered in the variable yourname. We also display an additional message saying “Hello” to the name entered in the input.

...
var yourname = prompt("What is your name");
alert("Hello, "+yourname);
...

 

The following is an example in which the above program actually operates once a button is pressed. alert("Hello, "yourname);
}


Look at the following program. How does it work?

 

...
var num1 = prompt("Enter the first value");
var num2 = prompt("Enter the second value");
alert(num1 + num2);
...

You may think that the above program stores two different numbers in the variables num1 and num2 respectively, adds both numbers and displays the sum. However, in reality, this is not how it works. We can try this using the buttons created below. Try and see the results for yourself.


As you may have noticed, since the two entered values ​​are treated as character strings instead of numbers, the operator + is interpreted as an addition of character strings, that is, concatenation of character strings into one word. If you want to add numeric values, you need to convert the string to a number. If you use Number () to do the following, it works as expected.

 

...
var str1 = prompt("Enter the first value");
var str2 = prompt("Enter the second value");
var num1 = Number(str1);
var num2 = Number(str2);
alert(num1 + num2);
...

 

An example of the operation is as follows.
var str2 = prompt("2つ目の値を入力してください。");
var num1 = Number(str1);
var num2 = Number(str2);
alert(num1 + num2);
}


Random Numbers

What are Random Numbers?


A program describes the various processing activities to be performed by the computer. Basically, program operation is determined by describing that the operation has changed depending on some condition, lest the same process is repeated or looped. However, some algorithms require randomly chosen values ​​(random numbers) like the Monte Carlo method. Many programming languages ​​have functions for generating such random numbers.

Math.random()

To generate random numbers in JavaScript, use Math.random (). Math.random () is a call to the random () method of the Math object, but the Math object is described elsewhere. There is no need to write all the code behind the Math object, it is already written for you to use.

When called, Math.random () returns a number greater than or equal to 0 and less than 1. What value will come back will be different depending on the time.

For example, see the following program. In this program, Math.random () is called, the return value is assigned to the variable num, and its value is displayed on the next line. Press the button of the operation example several times to see that different values ​​are displayed each time you press the button.

var num = Math.random();
alert("The random number is " + num)

}


 

Overview of Conditional Branching


When you write a program, you may want to change the behavior of the program depending on the input value etc. Conditional branching is what realizes such a function. In JavaScript, an if statement and a switch statement are prepared for conditional branching.

 

Conditional Expressions

Comparison Operations

In order to change the behavior of the program depending on the condition, it is necessary to memorize the method for describing conditional statements.

In many programming languages, there is a kind of operation that returns whether an expression is true or false. In other words, one can also use operators to describe conditions.

 

Operator Meaning Example
== Equality operator. It compares the left and right values. Returns true if they are the same, false otherwise. a == b、sum == 100
!= Inequality operator. Whether the left and right values are the same is judged. Returns true if they are different, false if otherwise. a != b、sum != 100
< It judges whether the value on the left is lesser than the value on the right. Returns true if it is small, false if otherwise. a < b、sum < 100
> It judges whether the value on the left is greater than the value on the right. Returns true if it is small, false if otherwise. a > b、sum > 100
<= It judges whether the value on the left is lesser than or equal the value on the right. Returns true if it is less than or equal, false if otherwise. a <= b、sum <= 100
>= It judges whether the value on the left is greater than or equal to the value on the right. Returns true if it is greater than or equal, false if otherwise. a >= b、sum >= 100

 

String Comparison

You can also use comparison operators in strings. In this case a little caution is necessary. When comparing the size of character strings, they are compared in alphabetical order. Therefore, “3” <“5″ , ” 12 “<” 3 ” , ” abc “<” def ” are all true. However, in the case of Japanese, it is a little more complicated. Within the computer, characters are represented by numbers called character codes (there are multiple codes such as JIS, EUC, Unicode). Characters are determined by the order of this character code, not according to alphabetical order.

Logical Operators

In order to describe more complicated conditions, it is necessary to combine several conditions. For example, if you want to describe a condition that a number num is greater than 3 and less than 10, you must satisfy two conditions: 3 <num and num <10. In such a case, there is what is called a logical operator to combine expressions. The logical operators are listed below.

 

Symbol Meaning Example Explanation
&& Logical AND. and operation. It becomes true when both the left and right are true. 3 < num && num < 10 num is greater than 3 and less than 10
|| Logical OR. or operation. True if either or both of the left and right are true. num < 3 || 10 < num num is greater than 3 or less than 10
! denial. not operation. Returns false if the value to evaluate is true, true if false. !(num < 3) num is not less than 3

 

If you want to describe a condition that a certain number num is larger than 3 and smaller than 10, write “3 <num && num <10” using the above logical product. You can not write like “3 <num <10”, so you need to be careful.

There is also a priority in logical operations as arithmetic operations such as sum-difference product quotient have priorities. Priorities of logical operations are “!”, “&&”, “||” in descending order of priority.

Logical operations have various features. For example, denial of negation is affirmative. Using logical operation “[comparison operation]” is the same as “!! [comparison operation]”. “Below” means “not greater than”. There is also a famous law called “de Morgan’s law” in the logical operation. Among them, “! ([Comparison operation 1] && [comparison calculation 2])” guarantees that it is the same as “! [Comparison operation 1] ||! [Comparison operation 2]”. Similarly, “! ([Comparison operation 1] ∥ [comparison operation 2])” is the same as “! [Comparison operation 1] &&! [Comparison calculation 2]”.

if statements、if-else statements

Basic if-statement

The use of the most basic if statement is to execute a part of the program only when a certain condition holds. What is shown in the following figure is called a flowchart, and it is one of methods for expressing the program flow. In this figure, the flow of an if statement is shown. In the if statement, processing is performed only when a certain condition is satisfied, and the most basic way of writing it is to do nothing if it does not hold.

 

 

The if statement which behaves like the above figure is expressed as follows. In the parentheses of the condition of the if statement, a conditional expression describing combinations of comparison operators and logical operators as described above is written.

If the condition expression seems to return a true value, the part enclosed in curly brackets is executed. When the conditional expression does not hold, that is, when it becomes false, it will not be executed in the curly brackets and will proceed to the next command.

 

if (condition) {
/* *
Processing block executed only when the condition is satisfied
*/
}

 

The else clause of the if statement

In the above basic if statement, the block enclosed in curly brackets was executed only when the condition was satisfied. However, when writing various programs, there are cases where you want to execute process 1 if the condition is satisfied and process 2 if it is not. It is possible to write the reverse conditional statement using the logical operator ‘!’ And execute the process 2, but it is unlikely to be a wise way. In order to meet such needs, the if statement in JavaScript can be written as an else clause. The notation when using the else clause is as follows.  
if (condition) {
/* *
Processing block executed only when the condition is satisfied
*/
} else {
/* *
* Processing block executed only when the if condition is not
* satisfied
*/
}

It is shown in the flowchart as follows.

else if

It is also possible to specify more detailed conditions using an if statement. “○ ○ ○ when it is ○ ○, △△△ when not △ △, □□□ when not □ □, □□□ when not □ □,  □ ○ will be executed”. In order to describe such a conditional branch, conditions are confirmed in sequential order from top to bottom, and only the ones that apply first are executed. If a certain condition 1(ex: num <10) applies exactly to another condition 2 (eg num <100), condition 1 will never be executed unless it is  is written first.  
if (condition 1) {
/* *
* Processing block executed only when condition 1 is
* satisfied
*/
}
else if (condition 2) {
/* *
* Processing block executed only when condition 1 is not satisfied
* and condition 2 is satisfied
*/
} else if (condition 3) {
/* *
* Processing block executed only when condition 1 to condition 2
* are not satisfied and condition 3 is satisfied
*/
...
} else if (condition n) {
/* *
* Processing block executed only when condition 1 to condition n-1 * are not satisfied and condition n is satisfied
*/
}

You can join any number of else if statements. Also, at the end, if you wish to include the part of “execute ○ ○ if none of the conditions are met”, do as follows.  

if (condition 1) {
/* *
* Processing block executed only when condition 1 is
* satisfied
*/
} else if (condition 2) {
/* *
* Processing block executed only when condition 1 is not satisfied
* and condition 2 is satisfied
*/
} else if (condition 3) {
/* *
* Processing block executed only when condition 1 to condition 2
* are not satisfied and condition n is satisfied
*/
...
} else if (condition n) {
/* *
* Processing block executed only when condition 1 to condition n-1
* are not satisfied and condition n is satisfied
*/
} else {
/* *
* Processing block executed only if none of the conditions
* apply
*/
}

 

Example of a program using an if statement

Let’s see an example of an actual program using an if statement. See the program below. When you press the button in the HTML part, the part that jumps to the function is already mentioned. In JavaScript, the second line prompts input from the user and stores the value in the variable str. Since the value stored in the variable str is handled as a character string here, it is converted to a numerical value using Number () on the next line, and it is stored in the variable num again. Moreover, we branch from line 5 using an if statement. In line 5, we check whether the value num input to the form is 2 and whether the remainder is 0 or not. That is, we check whether num is a multiple of 2 or not. If it is a multiple of 2, it executes in the immediately following block. That is, a message “It is a multiple of 2” is displayed. If it is not a multiple of 2, jump to the else if line 8. Here, we check whether num is a multiple of 3 or not. In the case of a multiple of 3, as in the case of multiples of 2, execute the subsequent block and display the message “It is a multiple of 3”. If it is neither a multiple of 2 nor a multiple of 3, it jumps to the last else clause and displays the message “It is neither a multiple of 2 nor a multiple of 3”. HTML part
<button onclick="iftest()">Example using statements</button>. 

JavaScript part

function iftest() {

 var str = prompt("Enter a number");
 var num = Number(str);

 if (num % 2 == 0) {
  // Alert for 2 alert("The number is divisible by 2");
 } else if (num % 3 == 0) {
  // Alert for 3 alert("The number is divisible by 3");
 } else {
  // If indivisible by either
  alert("The number is neither divisible by 2 nor 3");
 }

} 


In the above program, what will happen if you enter a number that is a multiple of 2 or a multiple of 3, such as “6” or “12”? Will both “both being multiples of 2” and “being a multiple of 3” be displayed? Recall that the program basically runs from top to bottom. When “6” or “12” is input, it is evaluated first by the if statement of the fifth line. Since “6” and “12” are multiples of 2, the conditional expression of this if statement is satisfied and the message “is a multiple of 2” is displayed. Once it matches the condition, the else if and else after that will be skipped. Therefore, when a numerical value that is a multiple of 2 or a multiple of 3 such as “6” or “12” is input, only the message “It is a multiple of 2” is displayed.

switch statements

The mechanism for conditional branching of JavaScript is a switch statement. The switch statement is a control portion that branches to multiple options according to what value the evaluation result of the expression takes. It is convenient to branch into multiple choices depending on the evaluation result of the same expression, because it can be described easily from the if statement. Conversely, a conditional branch that can be written with a switch statement is complicated, but it can also be written in an if statement.

Next is an example using a switch statement. In this example, the user inputs either “morning”, “daytime”, “evening”, or “night”, and the words of greeting are changed by inputting.

If the value of the expression in the parentheses of the switch statement matches one of the values ​​after the multiple case clause, the function is executed from the alert () function on the next line.

When a break statement appears in execution, the switch statement ends. If there is no break statement, it will be executed as it is until the following  case clause. For example, in the example below, if you type “evening”, the part under the next “case” night “is executed as it is.

Also, if it does not match any case clause, it is executed from the line following the default clause.

var word = prompt("Type Morning/Afternoon/Evening/Night for the time");
switch (word) {
case "Morning":
alert("Good Mordning。");
break;
case "Afternoon":
alert("Good Afternoon");
break;
case "Night":
case "Evening":
alert("Good Evening。");
break;
default:
alert("We cannot understand");
}


Exercise 3-1


Create a button so that the message
“What is the weather like today?” is displayed. Accept inputs for “Sunny”, “Rainy”, “Windy”, “Snowy” and “Cloudy”. When the user inputs “Sunny”, display the message “Have a wonderful day!”. Think of appropriate messages for other weather conditions. If the user inputs anything other than the predetermined weather conditions then ask the user to try again.

Exercise 3-2

Create a fortune teller program using the Math.random() function in JavaScript. If the number is less than 0.1, display “Bad Luck”, if it is between 0.1 and 0.33 display “Some Luck”, if it is between 0.33 and 0.66, display “Good Luck”, and if it is between 0.66 and 1 display “Amazing Luck!”. Use alerts to display your messages.

Exercise 3-3


Create two buttons, one for a conditional branch with an if-else statement and one for a switch-case statement for the following program.

When you press a button, the prompt “Please answer the what dinner you would like today using one of the keywords: Western / Japanese / Chinese / Other” is displayed, and according to each input, recommended restaurants are displayed in an alert.

Exercise 3-4


When you press a button, the prompt “What day of the week?” Is displayed, and when you enter the day of the week, the prompt “Period?” is displayed next. When you enter the period, the subject you are taking is shown using an alert.

Create a program to do this. However, if you enter a day of the week that does not have any classes display an alert “No Class!”.