The JavaScript Diaries: Part 5
Conditional Expressions
There is another method for writing conditional statements, so long as it is a true or false statement. This method uses the conditional operator ( ?: ). Consider the following script:
var yourAge = prompt("Please enter your age:", "");
if (yourAge >= 18) {
alert("You are a grownup");
}
else {
alert("You are a minor");
}
We've seen this type of script before so we don't need to go into how it works. Using a conditional statement, the same script could be written:
var yourAge = prompt("Please enter your age:", "");
var yourStatus = (yourAge >= 18) ? "grownup" : "minor"
alert("Your are a " + yourStatus)
Here, we declare and initialize the variable yourAge, as in the
previous script, but in this case, the entire if/else statement
is accomplished on one line. The second line declares and assigns a value to
the variable yourStatus depending upon the conditional statement
that follows it. The conditional statement reads: "If the variable yourAge
is greater than or equal to 18 then the value of the variable yourStatus
is 'grownup,' otherwise the value is 'minor.'"
Nesting
A conditional statement can also be contained within another conditional statement. This is called nesting. Consider the following script (with credit to John Pollock):
var have_cookbook="yes";
var meatloaf_recipe="yes";
if (have_cookbook=="yes") {
if (meatloaf_recipe=="yes") {
alert("Recipe found");
}
else {
alert("Have the book but no recipe");
}
}
else {
alert("You need a cookbook");
}
Let's look at how this script is executed:
|
It sounds a little complicated but if you look closely you'll see it's pretty straightforward.
You could also nest a conditional statement within the bottom (outside) else block. In other words, the same nested block that you see above could also be done in the other part of the statement:
var have_cookbook = prompt('Do you have a cookbook?','');
var meatloaf_recipe = prompt('Do you have a meatloaf recipe?','');
var have_web_access = prompt('Do you have access to the Web?','');
if (have_cookbook=="yes") {
if (meatloaf_recipe=="yes") {
alert("Recipe found");
}
else {
alert("Have the book but no recipe");
}
}
else {
if (have_web_access=="yes") {
alert("Find the recipe on the Web");
}
else {
alert("You need a good cookbook");
}
}
There's no limit to the number of nested statements you can use. While they seem to be a bit confusing, if taken a step at a time, they can be a very powerful tool.






Loading Comments...