1. Technology
Send to a Friend via Email
The IF Statement

Introduction

In the last tutorial you learned about operators that you can use to manipulate text and number variables. In this tutorial we are going to look at a couple more types of operators. These operators are commonly used in if statements.

  • Relational operators compare two variables (regardless of type) and evaluate to a boolean value (true or false) and
  • Logical operators compare two boolean values (either variables or the result of a relationship operator) and evaluate to a boolean value.

Comparing Values

Let's look at an example that includes an if statements using the equals (==) relationship operators

<script language="javascript" type="text/javascript">
var red = 5;
var blue = 3;
var match = null;
if (red == blue) {
   match = 'equal';
} else {
   purple = 'unequal';
}

document.write(red + ' and ' + blue + ' are ' + match);
</script>

The equals relationship operator compares the values held in the "red" and "blue" variables. If they are the same then "red == blue" evaluates as true. If they are not the same (as is the case with the code that we have here) then it evaluates to false.

An if statement selects which of two pieces of code to execute depending on whether the contents within the parentheses evaluates as true or false. If it evaluates as true then the code between the braces following will be executed (in this example the statement: match = 'equal'). If it evaluates as false and the if statement has an else clause as this one does then the code preceding the else will be skipped over and the code contained in the braces following the else (in this example the statement: match = 'unequal') will be executed instead.

If an else clause is present and the if statement evaluates as true then the content in the braces following the else clause will be skipped over.

If an else clause is not present and the if statement evaluates as false then the code within the braces will be skipped over and next statement will be executed.

The braces are used to group statements together. In this example only one statement is contained within each group and so the braces are optional and can be omitted. The braces must be present where more than one statement is to be evaluated in either the true or false branch of the if statement.

One common error that is made when coding if statements is to only code one equals instead of two. The statement if (red = blue) will assign the content of the blue variable to the red variable first (in the above example red would be set to 3) and this value would then be evaluated as true or false. When an if statement evaluates to a numeric value then it is always considered to be true except where the number is zero and so in this case match would incorrectly be assigned 'equal'. The single equals represents an assignment, you need two equals together to compare fields.

Of course we may not want to test if two fields are equal and so there are other relational operators that we can use to perform other types of comparisons. The following code fragments show some examples:

if (red > blue)
if (red >= blue)
if (red < blue)
if (red <= blue)
if (red != blue)

The first of these will evaluate as true if the number in the red variable is greater than that in the blue variable. If these were text fields then it would evaluate as true if the characters in red have higher ascii values than those in blue. Mostly text fields will evaluate in alphabetical order since the alphabet occupy successive entries in the ascii code table however the upper and lower case characters occupy separate areas of the table with lower case having higher values than upper case. What this means is that 'Z' is greater than 'A' but less than 'a'.

The others evaluate for greater than or equal, less than, less than or equal, and not equal respectively.

Multiple Comparisons

Of course there will be times when you need to test more than one comparison in the same if statement and this is where the two logical operators come into use. Here is an example:

<script language="javascript" type="text/javascript">
var red = 5;
var blue = 3;
var green = 3;
var match = null;
if ((red == blue) && (red == green)) {
   match = 'equal';
} else {
   purple = 'unequal';
}
document.write(red + ' and ' + blue + ' are ' + match);
</script>

In this example the value in red must equal both the value in blue and the value in green for the if statement to evaluate as true. If either comparison evaluates as false then the entire if statement evaluates as false. Had we wanted to test if the value in red matched the value in blue or the value in green then we would have used the following if statement:

if ((red == blue) || (red == green))

With this code if the either condition is met the if statement evaluates as true and the else code would only be run if both conditions evaluate as false.

You will notice that I have placed parentheses around each comparison. If you code your if statements this way then you have complete control over the order in which the comparisons are performed. If you leave out the parentheses then they may not be compared in the order that you expect leading to unexpected results.

There is one more version of the if statement that you may occassionally see. This version doesn't use if and else. Instead it uses ? and :. The part of the statement preceding the question mark is the condition to be evaluated. If that condition is true then the code between the question mark and colon will be executed if false then the code foloowing the question mark will be executed. So instead of:

if (red == blue) {
   match = 'equal';
} else {
   purple = 'unequal';

we could have specified:

red == blue ? match = 'equal' : match = 'unequal';

As you can see, this makes for much smaller but much less readable code.

Using What You Know

Imagine that you are selling something and sometimes you offer a discount. When a $2 discount is offered you want the page to read:

<p>Save $2 off the normal price of $25,
now only $23.</p>

During those periods where a discount is not offered you want the page to read:

<p>Buy now at our regular cheap price of $25.</p>

This time the text for the two situations are completely different from one another. Of course again this is no problem with Javascript.

var discPrice = 25;
var regPrice = 25;
var discount = regPrice - discPrice;
if (discount > 0)
document.write('<p>Save $'+discount+' off the normal price of $'
+regPrice+ 'now only $'+discPrice+'.</p>');
else
document.write('<p>Buy now at our regular cheap price of $'
+regPrice+'.</p>');

Simply change the value of discPrice to the actual selling price and the message will change appropriately between the two alternatives.

You can opt-out at any time. Please refer to our privacy policy for contact information.
Related Video
How to Use Ornamental Grasses in Gardens
How to Properly Clean a Toilet

©2014 About.com. All rights reserved.