Notes 11
— print (last updated: Jul 15, 2009) print

Select font size:

Decision-making operations

These programs incorporate the decision-making operations in order to permit different behaviors for non-standard inputs. The decision statements we will use are called if/else statements and are of the many available control structures in JavaScript.

Think of control structures as programming elements which alter the flow of statement execution. The normal flow is to execute statements sequentially from the top down. The effect of control structures allows us to skip over certain statements or else go back and repeat statments (loops).

Cancel Pressed in the prompt function

To begin, we want to modify the program from Notes 10 to respond appropriately when Cancel is pressed.
<script type="text/javascript">
<!--
var str = prompt( "Enter your name!", "YOUR NAME" ) 
document.writeln( "Hello " + str + ", how are you" ) 
// -->
</script>
When cancel is pressed str has the value null. What we need is a statement that tests whether str is null and does something different. Consider this variation:
<script type="text/javascript">
<!--
var str = prompt( "Enter your name!", "YOUR NAME" ) 
if (str == null)
  alert( "Cancel was pressed" ) 
else
  document.writeln( "Hello " + str + ", how are you" ) 
// -->
</script>
Observe the behavior now when Cancel is pressed or not. This program introduces a decision statement. The one we are using is a basic if/else statement. The entire form
if (...) ... else ...
functions as a single statement.

The first part is this:

if (str == null)

which introduces a boolean operator == called equals. You have to be careful to distinguished it from the assignment operator = which has completely different behavior. The syntax

str == null
is called a boolean expression. The parentheses around this expression are required in order to construct the correct syntax for the statement. This boolean expression generates one of the two boolean values: true or false.

The behavior of the entire if/else statement is this:

Chaining decision operations

Run the above program and type a backspace when the prompt dialog appears to clear the text field, then type OK. You'll see the following:
Hello , how are you.
The name was the empty string. Suppose we want to prevent the output in this case, too. To do so, we will introduce a second decision:
<script type="text/javascript">
<!--
  var str = prompt( "Enter your name!", "YOUR NAME" )
  if (str == null)
    alert( "Cancel pressed" )
  else if (str == "")
    alert( "No name entered")
  else
    document.writeln( "Hello " + str + ", how are you" )
// -->
</script>
What you see represents a stylistic presentation of combined if..else statements. To be technically correct, it ought to look like this:
if (str == null)
  alert( "Cancel pressed" );
else 
  // the "else part" is itself an if..else statement
  if (str == "")
    alert( "No name entered") 
  else
    document.writeln( "Hello " + str + ", how are you" ) 
However, the previous presentation is preferred with the
else if
acting like a second test case. This helps avoid having to create too much indentation in a long series of chained tests.

Test the program in three cases: Our solution is not "perfect" in the sense that we would like to also prevent completion when the input consists of a blank string as well as the empty string.

Boolean operators: or, and, not

Boolean expressions, such as those created by ==, etc, can be combined by these three boolean operators:
  1. or operator, ||:
    boolean_expr1 || boolean_expr2
    is true if either of the components is true (or both are true), otherwise false
  2. and operator, &&:
    boolean_expr1 && boolean_expr2
    is true if both of the components is true, otherwise false
  3. not operator, !:
    ! boolean_expr
    is true if the expression is false and vice-versa
For example, we could write the previous program in a more economical way if we decide to give the same error message for the two input error cases:
<script type="text/javascript">
<!--
  var str = prompt( "Enter your name!", "YOUR NAME" ) 
  if (str == null || str == "")
    alert( "Invalid input") 
  else
    document.writeln( "Hello " + str + ", how are you" ) 
// -->
</script>

Cancelled or invalid numeric inputs

Now we'll consider the following program which squares a number:
<script type="text/javascript">
<!--
var str = prompt( "Enter a number", "" )   // prompt
var num = parseFloat(str)                  // string -> num
var result = num * num                     // compute square
document.writeln( num + "<sup>2</sup> = " + result )   // output
// -->
</script>
and enhance its behavior with decision statements so as to avoid computing when the input is cancelled or is an invalid numeric string. In both cases the num value returned from parseFloat will be "NaN".

The isNaN function

JavaScript has a dedicated global boolean function called isNaN (see global function table) which tests a numeric value and gives a true value if it is a NaN. The most obvious thing to do is to issue an alert if we discover that num is a NaN instead of going ahead with the computation:
<script type="text/javascript">
<!--
var str = prompt( "Enter a number", "" )   // prompt
var num = parseFloat(str)                  // string -> num
if (isNaN(num))
  alert( "Input Error" ) 
else {
  var result = num * num                   // compute
  document.writeln( num + "<sup>2</sup> = " + result )   // output
}
// -->
</script>

Compound statements

The above JavaScript program introduces the usage of of brackets { .. } to group multiple statements together and make them act as a single statement. Such a grouping is called a compound statement.

In an if..else structure, it is not a bad idea to make both the if and the else part compound, even when there is only one statement, in a format like this:
if (str == null) {
  // ... one or more statements
} else {
  // ... one or more statements
}

In order to see how statements are structured it is best to use a good style of line indentation.

Suppose we want to refine this and produce an alert specific to Cancel being pressed for the prompt function. In that case I want to test str == null immediately after the first line. If this is OK, I go on and test for NaN after using parseFloat.
<script type="text/javascript">
<!--
var str = prompt( "Enter a number", "" )   // prompt
if (str == null) {
  alert( "Cancel was pressed" ) 
} else {                          // something entered
  var num = parseFloat(str)       // make numeric
  if (isNaN(num))
    alert( "Input Error" ) 
  else {
    var result = num * num
    document.writeln( num + "<sup>2</sup> = " + result ) // output
  }
}
// -->
</script>
In this case we need two compound statements, one within the other.

The confirm function

There are cases in which we want to do something based on a decision being true and do nothing if the decision is false. In this case, we can simply leave out the keyword else. A good example usage employs the function window.confirm, or simply confirm.
document.writeln( "Begin" )
if ( confirm("Do you want to insert the middle?") ) {
  document.writeln( "Middle" );
}
document.writeln( "End" )

The confirm function's behavior is has features of both the alert and the prompt functions. It gives the user two choices: OK or Cancel. It returns a boolean value: true if OK was pressed and false if Cancel was pressed.

In this case, if we press OK, we will print the "Middle" word as well, otherwise not.


© Robert M. Kline