Web Development Tutorials




  
  

The if Statement

One of the most powerful features in JavaScript, and in computer languages in general, is the ability to make decisions. A script can be written to test some condition - normally the value contained in a variable - and to take alternate courses of action based on whether the condition tested is evaluated as true or false.

Script decision making takes place with the if statement, which has the following general format.

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

Figure 4-1. General format for if statement.

A conditional expression - one that can be evaluated as either true or false - is posited. If evaluation of the expression is true, then one or more statements within the braces are executed; if the expression is false, the statements are not executed. Thus, depending on the condition, either some processing takes place or it does not.

Conditional Operators

Conditional expressions used in if statements are tests of true or false conditions. These tests are set up using conditional operators to compare values. There are six basic condition tests that can be made using the operators listed in the following table.

Conditional
Operator
Comparison
== Equal operator.
value1 == value2
Tests whether value1 is the same as value2.
=== Identical operator.
value1 === value2
Tests whether value1 is identical to value2 in both value and type.
!= Not Equal operator.
value1 != value2
Tests whether value1 is different from value2.
!== Not Identical operator.
value1 !== value2
Tests whether value1 is different from value2 in both value and type.
< Less Than operator.
value1 < value2
Tests whether value1 is less than value2.
> Greater Than operator.
value1 > value2
Tests whether value1 is greater than value2.
<= Less Than or Equal To operator.
value1 <= value2
Tests whether value1 is less than or equal to value2.
>= Greater Than or Equal To operator.
value1 >= value2
Tests whether value1 is greater than or equal to value2.

Figure 4-2. Conditional operators.

A conditional expression is formed by relating values - either variables or constants - with these operators. The comparison is evaluated as Boolean true or false, and the script reacts to that condition. The following script presents a simple example of script decision making.

window.onload=init;

function init() {
   var ShowAlert = document.getElementById("ShowAlert");
   ShowAlert.onclick=ConfirmAlert;
}

function ConfirmAlert() {
  var Response = confirm("Do you wish to display the alert?");
  if (Response == true) {
     alert("Here is the alert.");
  }
}

<input type="button" value="Show Alert?" id="ShowAlert">

Listing 4-1. Code to test a condition.

A button click calls the ConfirmAlert() function where a confirm box asks to verify whether an alert message should be displayed. If the "OK" button is clicked, the Boolean value true is stored in variable Response; if the "Cancel" button is clicked, the value false is stored in variable Response. Then, the if statement checks the value of Response. If it is true, the alert message is displayed; if it is false, no action is taken.

Testing Variables and Statements

The if statement resolves any condition tested to either true or false, and it performs its processing only when the condition tested resolves to true. In effect, the if statement works as follows.

if (true) {
   do this...
}

Thus, any statement that resolves to true is, itself, the condition for executing the statements within the if construct.

In the previous example, the value returned from the confirm() method and stored in variable Response is either a true or false value. Therefore, variable Response, itself, resolves to true or false, and it is not necessary to express the test as (Response == true). The test (Response) is, itself, a test for a true condition.

var Response = confirm("Do you wish to display the alert?");
if (Response) {
   alert("Here is the alert.");
}

Listing 4-2. Alternate code to test a condition.

In fact, since the value returned from the confirm() method is a true or false value, the method itself can be used as the condition test; it is not necessary to assign its returned value to the intermediate Response variable.

if (confirm("Do you wish to display the alert?")) {
   alert("Here is the alert.");
  }

Listing 4-3. Second alternate code to test a condition.

You can use any of the above formats for checking true and false conditions. It is probably best, though, to use the format that is clearest for you to understand.


Logical Operators

Sometimes you need to combine condition tests. For instance, you might need to know if a numeric value is within a particular range, that is, whether the number is greater than one value and less than another value. Or, you might want to see if the number is outside a range by testing whether it is less than one value or greater than a second value. These kinds of combination tests are made possible by using logical (Boolean) operators to form multiple comparisons. These operators are listed in the following table.

Logical
Operator
Comparison
&& And operator.
condition1 && condition2
The condition1 and condition2 tests both must be true for the expression to be evaluated as true.
|| Or operator.
condition1 || condition2
Either the condition1 or condition2 test must be true for the expression to be evaluated as true.
! <Not operator.
! condition
The expression result is set to its opposite; a true condition is set to false and a false condition is set to true.

Figure 4-3. Logical operators.

Below is an example that uses a multiple condition test. After entering a value in the textbox, click the "Check" button. The script determines if you entered a number between 1 and 10 and, if so, confirms this value with a message to the page.


Enter a number between 1 and 10:


Figure 4-4. Performing multiple condition tests.

window.onload = init;

function init() {
   var btnCheck = document.getElementById("btnCheck");
   btnCheck.onclick = Check;
}

function Check() {
  document.getElementById("Output").innerHTML = "";
  
  var CheckValue = document.getElementById("DataIn").value;
  if (CheckValue >= 1 && CheckValue <= 10) {
     document.getElementById("Output").innerHTML = 
       "The number " + CheckValue + " is between 1 and 10";
    }
}
Enter a number between 1 and 10:
<input type="text" id="DataIn" style="width:40px">
<input type="button" value="Check" id="btnCheck"><br>
<span id="Output" style="font-weight:bold; color:red"></span>

Listing 4-4. Code to perform multiple condition tests.

A condition test is evaluated to see if the entered value is greater than or equal to 1 AND less than or equal to 10 (putting it in the range 1-10). Both condition tests must be true for the entire expression to evaluate to true. If the expression is true, a confirmation message is displayed by writing to the innerText property of the <span> tag.

Notice that the Output area is cleared when the function is called:

document.getElementById("Output").innerHTML = "";

This statement is necessary in order to erase any previous confirmation message when an invalid number is entered. An invalid entry should not be accompanied by a message left over from a previous valid entry.


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