Home

Conditional Statements

 

if a Condition is True

A script is usually executed in a top-down approach. Instead of letting the browser proceed as you wish, you can set a condition that would control the sequence of processing. If the  condition you set if true, then you can perform a desired operation. This processing is performed using the if condition. Its syntax is:

if(Condition)Statement;

When this statement executes, the Condition is checked. This condition comports an expression to be checked as true or false. The Condition is written between the parentheses that follow the if keyword. If the Condition is true, then the Statement would be executed. Suppose you want to find out if a club member applicant is still a teenager. You can compared the age of each applicant with the number 18 to validate his or her age. Here is an example:

if(MemberAge < 18) document.write("Teenager");

If the Statement is a small one, you can write the whole conditional expression on one line. If the Statement is too long, you can write it on its own line. The above statement can be written as:

if(MemberAge < 18)
document.write("Teenager");

If there are many lines of code that depend on the if condition, you must create a body for the if expression. To do this, include the Statement between an opening curly bracket "{" and a closing curly bracket "}". Everything between the brackets belongs to the if condition. Here is an example:

if(MemberAge < 18) {
document.write("Since you are still a teenager, ");
document.write("your application cannot be processed at this time.<br>");}
Even if the Statement is short or is made of just one line of code, you can use the curly brackets to delimit its beginning and end.

Indentation is very important when writing conditional statements. Even though the interpreter doesn't care about it, indentation makes your code easier to read. When indenting the statement part of a conditional expression, place it to the right under the if line so you would know where the condition started. After indenting the Statement portion, it is a good idea to write the closing bracket aligned under if. This makes it clear where the if condition started and where it ends. The above condition can be written as follows:

if(MemberAge < 18)
{
    document.write("Since you are still a teenager, ");
    document.write("your application cannot be processed at this time.<br>");
}

Practical Learning: Using the if Condition

  1. Start your text editor.
  2. In the empty file, type the following:
     
    <html>
    <head>
    <title>Slockum Enterprises - User Account</title>
    <SCRIPT LANGUAGE="JavaScript">
    function CheckPassword()
    {
      var Password, ConfPassword, Result;
      Password = document.frmRegistration.txtPassword.value;
      ConfPassword = document.frmRegistration.txtConfirmPass.value;
      Result = document.frmRegistration.txtResult;
      if(Password != ConfPassword)
        Result.value = "Your Passwords Do Not Match";
    }
    </SCRIPT>
    </head>
    <body>
    <h1>Slockum Enterprises</h1>
    <form name="frmRegistration">
        <p>&nbsp;</p>
        <table border="0" width="403">
          <tr>
            <td width="99">
        Full Name:</td>
            <td width="290"><input type="text" name="txtFullName" size = "32"></td>
          </tr>
          <tr>
            <td width="99">
        Username:</td>
            <td width="290"> <input type="text" name="txtUsername" size="15"></td>
          </tr>
          <tr>
            <td width="99">
        Password:</td>
            <td width="290"> <input type="password" name="txtPassword" size="15"></td>
          </tr>
          <tr>
            <td width="99">
        Confirm:</td>
            <td width="290">  <input type="password" name="txtConfirmPass" size="15"></td>
          </tr>
          <tr>
            <td width="99">
        Result:</td>
            <td width="290"> <input type="text" name="txtResult" size="40">
            </td>
          </tr>
        </table>
        &nbsp;
          <input type="button" value="Send It" onClick="CheckPassword()">
    </form>
    
    
    </body>
    </html>
  3. Save the file as registration.htm in your JavaScript Lessons folder
  4. Preview the file in your browser
  5. Enter a string in the Password text box and enter a different string in the Confirm text box
  6. Click Send It and see the result. Here is an example:
     
  7. After previewing the form, return to your text editor.
     

The if...else Condition 

The if condition we have just seen is used to find out whether a Condition is true. When it is true, we take an appropriate action. If the Condition is false, we simply ignore the whole thing. An alternative to the simple if condition is to take action when the Condition is false. Its syntax is:

if(Condition)
  Statement1;
else
  Statement2;

When the interpreter encounters this, it tests the Condition, possibly against a value. If the Condition is true, it executes Statement1. If the Condition is false, it executes Statement2. Either or both statements can consist of simple one-line expressions to perform. Here is an example:

if(MemberAge < 18)
  document.write("Teen membership not allowed at this time ");
else
  document.write("Congratulations - Membership Granted!!!");

Either or both could also be made of expressions of various lines. The rules we learned about the curly brackets can be used on each statement. Here is an example:

if(MemberAge < 18)
{
  document.write("Since you are still a teenager, ");
  document.write("your application cannot be processed at this time.<br>");
}
else
  document.write("Congratulations - Membership Granted!!!");
 
 

Practical Learning: Using the if...else Condition

  1. To apply an if...else condition, change the function as follows (the rest of the file doesn't change):
     
    <html>
    <head>
    <title>Slockum Enterprises - User Account</title>
    <SCRIPT LANGUAGE="JavaScript">
    function CheckPassword()
    {
      var Password, ConfPassword, Result;
      Password = document.frmRegistration.txtPassword.value;
      ConfPassword = document.frmRegistration.txtConfirmPass.value;
      Result = document.frmRegistration.txtResult;
      if(Password == ConfPassword)
        Result.value = "Congratulations - Account Created";
      else
        Result.value = "Your Passwords Do Not Match";
    }
    </SCRIPT>
    </head>
    <body>
  2. Save the file and test it in your browser
  3. After testing the file, return to your text editor

The if...else if...else Condition

The conditional expression we just studied is used to check if a condition is true or false. Some conditions can render more that two alternatives. In this circumstance, you can use the following syntax:

if(Condition1)
  Statement1;
else if(Condition2)
  Statement2;
else
  Statement_n;
if(Condition1)
  Statement1;
else if(Condition2)
  Statement2;
else if(Condition3)
  Statement3;
else
  Statement_n;

To perform this operation, the interpreter compares Condition1. If the comparison renders true, the interpreter executes Statement1. If the comparison produced a false result, the interpreter advances to Condition2. It compares Condition2. If the comparison renders a true result, Statement2 is executed. If the comparison produces false, the interpreter executes Statement_n. You can write as many else if conditions as you need to. If the interpreter examines each Condition and doesn't find any that is true, then it executes the statement of the else condition. In the following example, a store has decided to apply a discount on items depending on the price of the item:

if(ItemPrice <100)
  Discount = 0.10;
else if(ItemPrice < 200)
  Discount = 0.20;
else if(ItemPrice < 300)
  Discount = 0.35;
else if(ItemPrice < 400)
  Discount = 0.40;
 else
  Discount = 0.50;
 

Practical Learning: Using the if...else if Condition

  1. Start a new file in your text editor and type the following:
     
    <html>
    
    <head>
    <script language="JavaScript">
    function processCDOrder()
    {
        var quantity = parseInt(document.frmCDOrder.txtQuantity.value);
        var unitPrice, totalPrice;
    
        // The unit price of printing a CD will depend on the quantity order
        // The higher the quantity, the lower the unit price
        if( quantity < 20 )
     	unitPrice = 20;
        else if( quantity < 50 )
    	unitPrice = 15;
        else if( quantity < 100 )
    	unitPrice = 8;
        else
    	unitPrice = 5;
    
        totalPrice = quantity * unitPrice;
    
        document.frmCDOrder.txtUnitPrice.value  = unitPrice.toFixed(2);
        document.frmCDOrder.txtTotalOrder.value = totalPrice.toFixed(2);
    }
    </script>
    <title>CD Publisher</title>
    </head>
    
    <body>
    
    <h1>CD Publisher</h1>
    <form name="frmCDOrder">
      <table border="0" width="336">
        <tr>
          <td width="205">Number of CDs:</td>
          <td width="39"><input type="text" name="txtQuantity" size="10" value="0"></td>
          <td width="72"><input type="button" value="Calculate"
    			name="btnCalculate"  onClick="processCDOrder()"></td>
        </tr>
        <tr>
          <td width="209" colspan="3">Based on the specified quantity</td>
        </tr>
        <tr>
          <td width="205">Each CD will cost:</td>
          <td width="39"><input type="text" name="txtUnitPrice" size="10" value="0.00"></td>
          <td width="72"></td>
        </tr>
        <tr>
          <td width="205">And the total price is:</td>
          <td width="39"><input type="text" name="txtTotalOrder" size="10" value="0.00"></td>
          <td width="72"><input type="reset" value="New Order" name="btnNewOrder"></td>
        </tr>
      </table>
    </form>
    
    </body>
    
    </html>
  2. Save the file as CDOrder.htm in your JavaScript Lessons folder and preview it in your browser
  3. Type the number of CDs as 250 and click Calculate
  4. Return to your text editor

 

Switch Statements

As seen in the previous example an if...else statement can grow sometimes very large depending on the number of conditions to compare. JavaScript provides an alternative to a multitude of if...else conditions. It proposes a switch statement whose syntax is:

switch(Expression)
{
  case FirstCase:
    Statement1;
  case AnotherCase:
    Statement2;
  case YetAnother:
    Statement3;
}

When this statement is written, the interpreter first evaluates the Expression to get a value. Then it scans each case from top down to find which one matches the value of Expression. If it finds a case that matches the result of Expression, then it executes the corresponding statement. 

When writing the switch statement, provide an expression that can be appropriately evaluated. It could be a numeric value, a string, or even an expression; make sure the interpreter can get a value from it. On the right side of each case keyword, type a value that is of the same type as the value of the Expression. For example, if the Expression is a number, make sure each case is accompanied by a number. Here is an example:

switch(MembershipCategory)
{
  case 1:
    Fee = 100.00;
  case 2:
    Fee = 150.50;
  case 3:
    Fee = 175.00;
}

In JavaScript, the Expression can also be a string. In this case, make sure that the interpreter can determine it. Then type a valid and comparable string on the left of each case.

The switch syntax we have considered so far:

switch(Expression)
{
  case FirstCase:
    Statement1;
  case AnotherCase:
    Statement2;
  case YetAnother:
    Statement3;
  case OneMoreCase:
    Statement4;
}

Here is how this syntax works, the interpreter compares the Expression and gets a value. Then it compares this value with FirstCase. If the value of Expression and that of first case are the same, then the interpreter executes Statement1, Statement2, Statement3, and all Statementn under it. If the value of Expression and FirstCase are not the same, then the interpreter moves down to AnotherCase. If the value of Expression and AnotherCase match, then it executes Statement2, Statement3, and all Statementn under it. As you can see already, even after the interpreter finds a case match of the value of Expression, if that case is not the last one, there is a chance that the interpreter will executes statements that are not necessary. To make the interpreter execute only the statement that corresponds to the case that matches the value of expression, you must ask the interpreter to stop with that case. This is done by adding the break keyword at the end of each case. Therefore, a better syntax of the switch statement would be:

switch(Expression)
{
  case FirstCase:
    Statement1;
    break;
  case AnotherCase:
    Statement2;
    break;
  case YetAnother:
    Statement3;
    break;
  case OneMoreCase:
    Statement4;
    break;
}

The switch above can include as many cases as necessary. There is still a chance that none of the case would match the value of Expression. JavaScript proposes a special case that would include any value that is not one of the other listed cases. This is done by including the default case as in the following syntax:

switch(Expression)
{
  case FirstCase:
    Statement1;
    break;
  case AnotherCase:
    Statement2;
    break;
  case YetAnother:
    Statement3;
    break;
  case OneMoreCase:
    Statement4;
    break;
  default:
    DefaultStatement;
}

If none of the cases matches the value of Expression, then the interpreter would look for a default statement. If it finds one, then it executes it. The default case is executed if none of the cases can be used.
 

 

Previous Copyright © 2002-2004 FunctionX, Inc. Next