Selection

Javascript selection (or conditional) statements

Selection, or decisions, are made in Javascript using the statement

   if(condition) { //is true } else { //is false }
Simple if statements may be written as a single line, but when the true or false portions consist of multiple statements its more likely to be written as

   if (condition)
   {
      //is true
   }
   else
   {
      //is false
   }

You should note that the true statement block always comes first, followed by the false statement block. The programmer has no control over this order. Depending whether the condition is true or false, only the code in the selected block is executed.

It is a common mistake to put a semicolon after the condition, before the first curly brace.

Very often, if the condition is false, then the program action is to do nothing. In these circumstances the else keyword and the false block may be omitted, however in doing this, may have security implications.

To illustrate the if statement, a range check will be used. The task is to select integers in the range 97 to 122. A prompt box will be used to get a value from the user. An algorithm to do this is described by the following piece of structured English (or pseudo code).

Structured English (or pseudo code) version of algorithm

START
GET value from user
coerce value to be a number; if it is a number.
IF it is true value is a number then
    IF value greater than or equal to 97
        IF yes the value less than or equal to 122 then
            output TRUE
        ELSE
            output FALSE; to large
        ENDIF
    ELSE value is less than 97
        output FALSE; to small
    ENDIF
ELSE its not a number
    output "the value entered is Not a Number"
ENDIF
WRITE output
END

The code below shows this algorithm converted to Javascript.

Since we are only interested if the value is a number then for the next test we need to negate the false from isNaN(value) check. Javascript negation (NOT) is performed by an exclamation mark (!). so ! false = true.

The method to coerce a string data type to a number data type is a global function called parseInt(value).

Another global function called isNaN(value) is used to test if the value entered is a number. It returns true if the value is Not a Number (NaN), otherwise it returns false, i.e. it is a number.

Why do I need to coerce the string to be a number?

Numbers as you would expect are sorted from smallest to largest. String representations of numbers are not. you can check this with a simple test

 alert('97' < '122'); 

This will return false; since the string value 9 is largest than than the string value of 1.

How do I check what data type a value is?

Another simple test will do this, notice quotes around a number is a string. Values returned from prompt boxes are strings, even though they may look like numbers!

  alert("'97' is a a type of " + typeof('97') + " but 97 is a type of " + typeof(97));
 
	
function test()
{
  var output = "";
  var result = prompt("enter value in the range 97 - 122","");
  result = parseInt(result); //coerce to integer value
  if (!isNaN(result))  //check value is a number
  {
     if (result >= 97) 
     {
         //number is greater or equal to 97
         if (result <= 122 )
         {
            //AND number is less than or equal to 122
            output = true;
         }
         else
         {
            //number is greater 122
            output = false; 
         }
      }
      else
      {
         //number is less than 97
         output = false; 
      }
      output =  output ? "passed" : "failed";
  }
  else
  {
      output = "the value entered is " + result;
  }
  document.getElementById('output').innerHTML = output;
}

Logical operators

While the example above works perfectly well, the code can be simplified by making use of a logical operator. These are AND, OR and NOT, the latter you have already been introduced to.
Logical AND is represented by, && and logical OR is ||. NOT is an exclamation mark. !

The more condensed version combines these two tests into one using a logical AND statement In plain words the test becomes

 
   is value greater than or equal to 97 AND is value is less than or equal to 122? 
   IF TRUE then pass ELSE  FALSE, fail.

When one if statement is contained whether another, as in the condensed example above, the statements are said to be nested.

codeView.png
function range()
{
  var output = "";
  var result = prompt("enter value in the range 97 - 122","");
  result = parseInt(result); //coerce to integer value
  if (!isNaN(result))  //check value is a number
  {
     if (result >= 97 && result <= 122 )
     {
         //number is in range
         output = true;
     }
     else
     {
         //number out of range
         output = false; 
     }
  }
  else
  {
      output = "the value entered is " + result;
  }
  document.getElementById('output').innerHTML = output;
}

Forgetting to use a double | | (or && ) is a common source of programming error. A single | (or & ) performs a bitwise test (i.e. on the noughts, '0' and ones, '1',s that make up the binary code).

If and If ... Else syntax diagrams

The diagrams below show graphically how the syntax of the if () { ... } and if () {...} else {...} statements is built up.

If.png

IfElse.png

AttachmentSize
selection-Ex1.htm1.93 KB