The if Statement

The if statement has the following syntax:


if (condition) 
   statement1 
else 
   statement2

In the following code the conditional expression compares the value myAge against a numeric value of 13:

 
<!DOCTYPE html>
<html>
<head>
    <title>Example</title>
    <script type="text/javascript">

                 var myAge = 12;
                 if   (myAge    <  13) 
                 { 
                      document.writeln("under 13.");
                 } 

    </script>
</head>
<body>
</body>
</html>
  
Click to view the demo

The condition can be any expression.

JavaScript converts the result of the expression into a Boolean by calling the Boolean() casting function.

The following code output true:

 
<!DOCTYPE html>
<html>
<head>
    <title>Example</title>
    <script type="text/javascript">
    
        var i = 3;
        if (i){
            document.writeln("true"); 
        }
        else {
            document.writeln("false");
        } 
    </script>
</head>
<body>
</body>
</html>
  
Click to view the demo

You can also chain if statements together like:


if (condition1) 
   statement1 
else if (condition2) 
   statement2 
else 
   statement3

Here's an example:

 
<!DOCTYPE html>
<html>
<head>
    <title>Example</title>
    <script type="text/javascript">
    
        var i = 50;
        if (i > 25) {
           document.writeln("Greater than 25."); 
        } else if (i < 0) {
           document.writeln("Less than 0."); 
        } else {
           document.writeln("Between 0 and 25, inclusive."); 
        } 

       
    </script>
</head>
<body>
</body>
</html>
  
Click to view the demo
Home 
  JavaScript Book 
    Language Basics  

Statements:
  1. The if Statement
  2. The do...while Statement
  3. The while Statement
  4. The for Statement
  5. The for-in Statement
  6. Labeled Statements
  7. The break and continue Statements
  8. The with Statement
  9. The switch Statement