Nested Conditionals
A nested conditional is a conditional statement within the block of another conditional statement. For example:
let materialCovered = true;
let studied = true;
if (materialCovered) {
if (studied) {
console.log("We covered the material and I understand it");
}
else {
console.log("We covered the material but I do not understand it");
}
}
else {
console.log("We have not covered the material yet");
}
// Outputs: We covered the material and I understand it
When using nested conditionals, it is good to use indentation to avoid confusing yourself. Remember that a more indented block of code follows a {
.
Nested conditionals can often be rewritten as chained conditions using logical operators. Our example can be rewritten as follows:
let materialCovered = true;
let studied = true;
if (materialCovered && studied) {
console.log("We covered the material and I understand it");
}
else if (materialCovered && !studied) {
console.log("We covered the material but I do not understand it");
}
else {
console.log("We have not covered the material yet");
}
// Outputs: We covered the material and I understand it
It is important to realize that no method is "wrong." In different situations, one method may seem more logical, so feel free to use it.
Instructions
We need the program to print Passed with distinction
when the student has 75 or more points, Passed
when the student has 50 or more points, otherwise Failed
. On line 4, insert a nested if (points >= 75) {
that prints Passed with distinction
if true. If not (else
), it prints Passed
.
Start programming for free
8/9