Java Reference
In-Depth Information
For example, imagine you want to execute some code if myAge is in the ranges 30-39, 80-89, or 100-115,
using different code in each case. You could write the statement like so:
if ( (myAge >= 30 && myAge <= 39) || (myAge >= 80 && myAge <= 89) ||
(myAge >= 100 && myAge <= 115) )
{
document.write(“myAge is between 30 and 39 “ +
“or myAge is between 80 “ +
“and 89 or myAge is between 100 and 115”);
}
There's nothing wrong with this, but it is starting to get a little long and diffi cult to read. Instead, you
could create another if statement for the code executed for the 100-115 range.
else and else if
Imagine a situation where you want some code to execute if a certain condition is true and some other
code to execute if it is false. You can achieve this by having two if statements, as shown in the following
example:
if (myAge >= 0 && myAge <= 10)
{
document.write(“myAge is between 0 and 10”);
}
if ( !(myAge >= 0 && myAge <= 10) )
{
document.write(“myAge is NOT between 0 and 10”);
}
The fi rst if statement tests whether myAge is between 0 and 10 , and the second for the situation where
myAge is not between 0 and 10 . However, JavaScript provides an easier way of achieving this: with an
else statement. Again, the use of the word else is similar to its use in the English language. You might
say, “If it is raining, I will take an umbrella; otherwise I will take a sun hat.” In JavaScript you can say
if the condition is true , then execute one block of code; else execute an alternative block. Rewriting
the preceding code using this technique, you would have the following:
if (myAge >= 0 && myAge <= 10)
{
document.write(“myAge is between 0 and 10”);
}
else
{
document.write(“myAge is NOT between 0 and 10”);
}
Writing the code like this makes it simpler and therefore easier to read. Plus it also saves JavaScript from
testing a condition to which you already know the answer.
Search WWH ::




Custom Search