If and else statements in Javascript.

Using if and else statements

The ordinary if/else statement

  • Programs needs to take action based on a true condition, or another action based on a false condition.
  • For this we are using if and else statements which also both can be nested:
    With if and else With if, else if and else
      if (expression1) {
        if (expression2)
          statement1;
        else {
          if (expression3)
            statement2;
          else
            statement3;
        }
      }
      else
        statement4;
    if (expression1) {
        if (expression2)
          statement1;
        else if (expression3)
            statement2;
         else
            statement3;
      }
      else
        statement4;
    
    
    
    • If the expression followed by the if statements evaluates to true, statements after the if statement will be executed else the statements after a else starts executing.
    • If more than one statement exists for either the true or the false part you need to surround the statements with braces ({}).
    if & else example:
    <script type="text/javascript">
      // Demonstrates if/else and
      // proper use of braces
      // in nested if statements
      var number=4;
      number=prompt("Enter a number less than \n"
        +"5 or greater than 20:");
      if (number >= 5) {
        if (number > 20)
          document.write("Number is greater than 20!<br>");
      }
      else
        document.write("Number is less than 5!<br>");
    </script>

The Conditional (Ternary) Operator.

  • This is a short notation to use for a simple if & else statement:
    (expression1) ? (expression2) : (expression3)

    This is: if expression1 is true, return the value of expression2; otherwise, return the value of expression3.
    <script type="text/javascript">
      var num1=5, num2=4 ;
      var z = (num1 > num2) ? "num1>num2" : "num1<=num2";
      document.write(z);
    </script>
    

© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.