Javascript Tutorial -- If Statements



So far, all of the scripts we have studied so far operate in a more-or-less linear fashion. OK, technically, functions branch to a different block of code until returning to the main routine, but fundamentally the logic has flowed from top to bottom, executing each step in turn until completion in all of our scripts so far. So what happens if the script needs to make a decision somewhere along the line? Most modern programming languages, including Javascript, include conditional statements -- statements that will execute one block of code if some condition is true, and (optionally) some other block of code if the condition is false.

We will start with a simple example. Suppose you have two numbers, stored in the variables a and b. You want to print the bigger number to the web browser. Javascript's if statement will allow you to compare two (or more) items, and execute a command based upon the comparison. Here's how you do this in Javascript:
        <script type="text/javascript">
          <!--
            var a = 5
            var b = 7

            if (a > b)
              {
                document.write("The bigger number is " + a)
              }
            else
              {
                document.write("The bigger number is " + b)
              }
          //-->
        </script>
      
The general form of an if statement is...:
        if (test)
          {
            code to run if the test evaluates to true
          }
        else
          {
            code to run if the test evaluates to false
          }
      
Unlike in human languages (or at least Western languages; I'm not sure about other cultures), Javascript does not use the equals sign to test for equality. In Javascript, the equals sign is only used as an assignment operator. If you want to test for equality, you use two equals signs together, like this: "==". If you have a C or Perl background, this will seem familiar to you; otherwise, it might seem a little strange. Think of it this way...a single equals sign is an assertion ("a IS equal to b") whereas a double equals sign is a question ("is a equal to b?"). Here is a table showing the equality operators used in Javascript:

Operator Meaning
== Is Equal To?
< Is Less Than?
> Is Greater Than?
<= Is Less Than Or Equal To?
>= Is Greater Than Or Equal To?
!= Is Not Equal To?


Here is a sample script using if statements.