Creating JavaScript if Statements

Creating JavaScript if Statements

You use the if statement in JavaScript to test your data and to execute some code if the test is true. Here's the basic form of the if statement:

 if (  condition  ) {  code  } 

Here, condition is the test that you want to make, and code is the code you want to execute if the condition is true. One thing to note here is that you must enclose the code to execute in curly braces, { and } .

So what kind of conditions can you check, and how do you do so? To construct a condition to test, you use the comparison operators, such as < (less than), > (greater than), == (is equal to), <= (is less than or equal to), or >= (is greater than or equal to).

Here's an example. in this case, I'm making sure that the value in a variable named temperature is greater than 32 :

Listing ch06_06.html
 <HTML>     <HEAD>         <TITLE>             Using the JavaScript if Statement         </TITLE>     </HEAD>     <BODY>         <CENTER>             <H1>                 Using the JavaScript if Statement             </H1>         </CENTER>         <SCRIPT LANGUAGE="JavaScript">             var temperature             temperature = 45  if (temperature > 32) {   document.writeln("We're above freezing.")   }  </SCRIPT>     </BODY> </HTML> 

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

Figure 6-6. Using the if statement to check the temperature.

graphics/06fig06.gif

Here are some other if statement examples:

 if (year == 2001) {     document.writeln("The year is 2001.") } if (color == "red") {     document.writeln("Stop the car.") } if (price < 2000.00) {     document.writeln("Be careful, the price has fallen too low!") } 

Besides using the comparison operators, you can use the and operator, && , and the or operator, , to combine conditions. Here's how you can use the && operator:

 if (temperature < 75 && temperature > 65) {     document.writeln("We're in the comfort zone.") } 

Here, the value in the variable named temperature must be less than 75 and greater than 65 for the code to be executed. If the temperature is indeed in that range, the message We're in the comfort zone . is displayed.

In this example, both conditions must be true for the overal condition to be considered true. However, you can use the operator as well to connect conditions. Here's an example:

 if (temperature < 65  temperature > 75) {     document.writeln("Outside the comfort zone!") } 

In this case, if the value in temperature is less than 65 or greater than 75 , the overall condition is considered true and the code is executed, which means that the message Outside the comfort zone! is displayed in the Web page.



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