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.
first = prompt("Enter a number:", "");
second = prompt("Enter another number:", "");
firstNumber = parseInt(first);
secondNumber = parseInt(second);
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
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.
|