Javascript if decision

JavaScript uses an if statement to select between two alternative paths. Put this script into a page and try it. Remember that it needs to be between the script tags.

// Ask for two numbers and compare them.
first = prompt("Enter a number:", "");
second = prompt("Enter another number:", "");

// The prompt has give us strings but we need
// numeric values for the comparison
firstNumber = parseInt(first);
secondNumber = parseInt(second);

// Now tell the user which number was bigger
if(firstNumber > secondNumber)
   document.write (first + " is bigger.");
else
   document.write (second + " is bigger.");

The first bit of the program should be familiar by now. We're asking the user for two numbers, we know that they're going to come in as strings so we use parseInt() to convert them into numeric values.

Then we come to the new bit - the if structure.

This starts with the word if which has to be followed by an expression in brackets which can be evaluated to give a logical value of true or false. If the expression is true then the next statement will executed. If the expression is not true then the statement after the else will be executed.

Using else

The else half of this structure is optional. You could have just written:

if(firstNumber > secondNumber)
   document.write (first + " is bigger.");

In this case nothing at all would happen if the expression evaluated as false. This might have been what you wanted but it's safer to make a habit of always writing out the entire structure:

if(firstNumber > secondNumber)
   document.write (first + " is bigger.");
else
   // No need to do anything here - user isn't interested.

Braces

The if and else clauses can each only control a single statement. In this simple example, there's only a single line in each half of the structure and the JavaScript program runs without error. Most realistic programs are more complicated than this and JavaScript allows us to use a pair of braces to group multiple lines into a single statement:

if(firstNumber > secondNumber)
{
   document.write (first + " is bigger.");
   document.write ("and");
   document.write (second + " is smaller.");
}
else
{
   document.write (second + " is bigger.");
   document.write ("and");
   document.write (first + " is smaller.");
}

This technique of using braces to gather lines together into a block is used in a lot of places within JavaScript.

MS Access technical tips

Visual FoxPro technical tips

General Tips

 

More tips from Alvechurch Data

Search page for Alvechurch Data

Searching a web site with JavaScript

Read More

Site Map

Site map of the Alvechurch Data site

Read More

Javascript while loops

JavaScript do and while loops

Read More

Javascript for loops

Javascript for loops

Read More

Repetition in Javascript

JavaScript structures for repetition

Read More