Web Development Tutorials




  
  

The if...else Statement

In previous examples, the if statement checks a condition and takes action on a true condition; it does not take action on a false condition. An alternate form of the if statement permits action on both true and false conditions.

if (conditional expression) {
   do this...
} else {
   do this...
}

Figure 4-5. General format for if...else statement.

Here, the script takes alternate courses of action depending on the results of the condition test. If the expression is evaluated as true, then the set of statements enclosed within the first set of braces is executed; if the expression is evaluated as false, the set of statements enclosed in braces following the else is executed. Thus, the script branches to one of two different processing actions that take place.

The following script is an example of the if...else form of condition testing.

window.onload = init;

function init() {
   var FirstBtn = document.getElementById("btnFirst");
   var SecondBtn = document.getElementById("btnSecond");

   FirstBtn.onclick=Display;
   SecondBtn.onclick = Display;
}

function Display() {
   if (this.value == "First Button") {
     alert ("You clicked the first button.");
   } else {
     alert ("You clicked the second button.");
   }
}

<input type="button" value="First Button" id="btnFirst">
<input type="button" value="Second Button" id="btnSecond">

Listing 4-5. Code for an if...else condition test.

The clicked button calls the Display() function, passing along the value of the button (this.value). Recall that the JavaScript keyword this is a self reference to the object containing the onclick event handler; the value property of this button is the value coded in the value="First Button" or value="Second Button" attribute.

If the value received is "First Button", then the condition test is evaluated as true and the alert box displays a message to that effect; else, the value received is not "First Button", the condition test is evaluated as false, and the alert box displays the alternate message.

Nested if Statements

Two or more if statements can be nested. That is, an if statement can appear inside an if statement, which can appear inside an if statement, and so forth. In a general form these nested if statements appear as follows.

if (conditional expression) {
  if (conditional expression) {
    do this...
  } else {
    do this...
  }
}
else {
  if (conditional expression) {
    do this...
  } else {
    do this...
  }
}

Figure 4-6. General format for nested if...else statements.

You need to be cautious about being too energetic in nesting if statements. It is easy to get lost in the logic and syntax when condition tests are nested to deep levels. Often, you can reformulate the logic of comparisons and make simpler combinations of tests.

In previous examples, the braces and enclosing statement blocks have been shown on separate lines and indented for visual emphasis.

if (conditional expression) {
   statements...
} else {
   statements...
}

You may, however, format the lines in other ways. The braces indicate enclosed blocks of code irrespective of how they appear visually in the if statement. The following examples show other ways of constructing syntactically valid if statements.

Example 1:
if (conditional expression)
{
   statements...
}
else 
{
   statements...
}

Example 2:
if (conditional expression) {
   statements...
} 
else {
   statements...
}

Example 3:
if (conditional expression) { statement } else { statement }

Listing 4-6. Alternate constructions of if...else statements.

What matters is that enclosing braces are properly paired, not how they appear visually. Choose a method that makes it obvious which statement block goes with which condition test.

Testing for Numbers

The situation often arises where it is necessary to check for a numeric value prior to performing calculations with the value. This is especially so when using user input within arithmetic calculations since nonnumeric data can cause script errors. Clicking the following "=" button to calculate the square root produces an error for the nonnumeric value in the textbox.


Square Root:

Figure 4-7. Producing an error with nonnumeric data.

The output textbox displays "NaN" indicating that the computation produced "Not a Number." This may be a satisfactory response; however, it is better to trap for invalid data to handle them through scripting rather than through default errors.

JavaScript provides the isNaN() function for just this purpose. When applied to a data value, the function returns true or false depending on whether the tested value is a number. A script can respond to either of these conditions.


Square Root:

Figure 4-8. Testing for nonnumeric data.

window.onload = init;

function init() {
   var btnSqRoot = document.getElementById("btnSqRoot");
   btnSqRoot.onclick = SquareRoot;
}

function SquareRoot() {
  if (isNaN(document.getElementById("Number").value)) {
    alert("Please enter a number.");
  } else {
    document.getElementById("Answer").value =
      Math.sqrt(document.getElementById("Number").value).toFixed(3);
  }
}

Square Root: 
<input id="Number" type="text" value="abc" 
  style="width:60px; text-align:right">
<input type="button" value=" = " id="btnSqRoot" > 
<input id="Answer" type="text" 
  style="width:60px; text-align:right">

Listing 4-7. Code to test for nonnumeric data.

Incidentally, the isNaN() function does not trap null characters, which are considered valid numbers. Therefore, if you want to disallow both nonnumeric and null characters in an input area, you must make separate tests. A rewrite of the previous if statement to make these tests is

if ( isNaN(document.getElementById("Number").value) ||
   document.getElementByid("Number") == "" )
   ...

The logical operator || (OR) is added to include a test for a null value. The full test becomes "if the value is not a number OR the value is null" then display the error message.


TOP | NEXT: if()... else.. if() Statements