The if Statement


The if Statement

As we've already seen, the if statement enables you to execute a series of statements if a test condition is true. The if statement also includes an optional else clause that holds code to be executed if the test condition was false. Here's what the syntax of this statement looks like, formally speakingnote that the code to execute is between curly braces, { and }:

 if (condition) {  statements1  }  [  else  {  statements2  }] 

The if statement and else clause are so fundamental to JavaScript that they've been in it from the beginning, as you can see in Table 2.10.

Table 2.10. The if Statement

Statement

NS2

NS3

NS4

NS6

IE3a

IE3b

IE4

IE5

IE5.5

IE6

if

x

x

x

x

x

x

x

x

x

x

Here's an example using the > (greater-than), < ( less-than ), and == (equality) comparison operators. In this case, I'm checking to see what kind of dinner people have voted for:

(Listing 02-15.html on the web site)
 <HTML>      <HEAD>          <TITLE>              Working With the if Statement          </TITLE>      </HEAD>      <BODY>          <H1>Working With the if Statement</H1>          <SCRIPT LANGUAGE="JavaScript">          <!--             var votesForPizza = 5              var votesForHamburgers = 6  if(votesForPizza > votesForHamburgers) {   document.write("Pizza wins!")   }   if(votesForPizza < votesForHamburgers) {   document.write("Hamburgers win!")   }   if(votesForHamburgers == votesForPizza ) {   document.write("Tie!")   }  // -->          </SCRIPT>       </BODY>  </HTML> 

Figure 2.13 shows the results. The if statement is at work finding out that hamburgers win.

Figure 2.13. Using the if statement.

graphics/02fig13.gif

Omitting the Curly Braces

Interestingly, if the code to execute in an if statement is only one line, you can actually omit the curly braces (although it's good form to still use them, as I'll do throughout the book):

 <HTML>      <HEAD>          <TITLE>              Working With the if Statement          </TITLE>      </HEAD>      <BODY>          <H1>Working With the if Statement</H1>          <SCRIPT LANGUAGE="JavaScript">          <!--             var votesForPizza = 5              var votesForHamburgers = 6  if(votesForPizza > votesForHamburgers)   document.write("Pizza wins!")   if(votesForPizza < votesForHamburgers)   document.write("Hamburgers win!")   if(votesForHamburgers == votesForPizza )   document.write("Tie!")  // -->          </SCRIPT>       </BODY>  </HTML> 

In JavaScript, curly braces make a series of single statements into one compound statement, called a block . The way the if statement is defined technically is to execute only one code statement if the if statement's condition is true; by using curly braces, however, you can make that single statement a compound statement that includes multiple single statements.

Since the early days, however, using curly braces to enclose the code an if statement should executeeven if that's only a single statementhas become accepted usage. This is true of many statements in JavaScript. In the next chapter, for instance, we'll take a look at the for loop; if you place only a single statement in a for loop's body, you don't need to enclose it in curly braces. In this book, however, I'll always use the curly braces for consistency.

The if statement also includes an optional else clause, and I'll take a look at that next.

Using else

An if statement executes its code if its test condition is true. You also can handle the case where you want the code to execute when a certain statement is false just use the ! logical NOT operator, which changes true to false and false to true:

  if(!(votesForPizza > votesForHamburgers)) {  document.write("Pizza loses.")  } 

What if you want to execute some code if the test expression is true, and other code if it's false? In that case, you can use an else clause. The code in an if statement executes if the test condition is true, and the code in the if statement's else clause, if present, executes if the test condition is false, enabling you to execute code either way.

In fact, we've already seen the else clause at work when we deleted an element from an array. In that example, if the element was not deleted, we displayed the message Still here! ; otherwise , because of the else clause, we displayed the message Sorry, that element is gone! :

 <HTML>      <HEAD>          <TITLE>              Working With the else Clause          </TITLE>      </HEAD>      <BODY>          <H1>Working With the else Clause</H1>          <SCRIPT LANGUAGE="JavaScript">          <!--           sandwiches = new Array("turkey","cheddar","ham","tuna","egg")            delete sandwiches[2]            if (2 in sandwiches) {  document.write("Still here!")   } else {   document.write("Sorry, that element is gone!")   }  // -->          </SCRIPT>       </BODY>  </HTML> 

This enables you to respond correctly when a test statement is trueand also when it's false. What if it's not just a question whether a test condition is just true or false? What if, for example, you want to handle the case where an expression is equal to 1, as well as the case where it's equal to 2, and 3, and 4, and so on? In that case, you need a switch statement, coming right up.

Tip

When thinking about if statements, don't forget about the conditional operator, ?: (discussed earlier in this chapter). It can function as a one-line if statement, making your code shorter and cleaner.


You also can use if else ladders of successive if and else statements, as in this example, as discussed more fully in Chapter 4, "Handling the Browser Environment":

 var object1  if (document.all){      object1 = document.all("IDobject1")  } else if (document.getElementByID) {      object1 = document.getElementByID("IdObject1")  } else if (document.layers) {      object1 = document.layers.document("NameObject1")  } 


Inside Javascript
Inside JavaScript
ISBN: 0735712859
EAN: 2147483647
Year: 2005
Pages: 492
Authors: Steve Holzner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net