Creating JavaScript ifelse Statements

Creating JavaScript if else Statements

In fact, the more general form of the if statement has an else clause, which can also hold code. The else clause is optional, but if you include it, the code in that clause is executed if the condition in the associated if statement is false. Here's how the if...else statement looks in general:

 if (  condition  ) {  code executed if condition is true  } else {  code executed if condition is false  } 

Here's an example showing how this works. In this case, I'm elaborating our previous example that made sure that the temperature is above freezing. I've added an else clause that is executed if the temperature is less than 32 °, and the code in that clause displays the message Time to drain the pool .:

Listing ch06_07.html
 <HTML>     <HEAD>         <TITLE>             Using the JavaScript else Clause         </TITLE>     </HEAD>     <BODY>         <CENTER>             <H1>                 Using the JavaScript else Clause             </H1>         </CENTER>         <SCRIPT LANGUAGE="JavaScript">             var temperature             temperature = 5             if (temperature > 32) {                 document.writeln("We're above freezing.")             }  else {   document.writeln("Time to drain the pool.")   }  </SCRIPT>     </BODY> </HTML> 

You can see the results of this code in Figure 6-7.

Figure 6-7. Using the else clause.

graphics/06fig07.gif



Real World XML
Real World XML (2nd Edition)
ISBN: 0735712867
EAN: 2147483647
Year: 2005
Pages: 440
Authors: Steve Holzner

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