Book
Submodule 7.3: Applying the "if" statements
Submodule 7.3: Applying the "if" statements
Completion requirements
View
- Confirm interaction
- Nested conditionals
- Temperature converter
Nested conditionals
Nested conditionals are actually conditionals inside a conditional.
if (expression1){
/*this code runs if expression1 evaluates to true*/
if (expression2){
/*this code only runs if both expression1 and expression2 evaluate to true*/
}
} else {
/*this code runs if neither are true*/
}
Example
In the below example, we have used nested conditionals to define whether we need to ask more input from the user.
The logic of the below code is: if the user likes bananas then display a message, else ask him his favorite fruit. If the user doesn't like bananas and prefers apples then display a message, else if he doesn't like bananas and prefer other fruit than apples, display another message.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Nested contitionals </title>
</head>
<body>
<h3> Nested contitionals</h3>
<script>
var likeBananas;
var favoritFruit;
likeBananas = confirm("Do you like bananas? ([OK] for yes, [Cancel] for no)");
if (likeBananas) {
document.write("You like Bananas!")
} else {
favoritFruit = prompt("What is your favorite fruit")
if (favoritFruit == "apples") {
document.write("You like apples! Me too!")
}else {
document.write("You like " + favoritFruit + "! I prefer apples!")
}
}
console.log ("All fruits are good!");
</script>
</body>
</html>
Exercise
- Open your editor, create a new file and save it as
exersice07.3.02.html
in the folder "Exercises". - Copy the above code and paste it in the new file.
- Save the file. Experiment by changing the values of the variables.