5.5. Nested Conditionals¶
/*Our first attempt at a solution might look like this:
(NOT USING NESTED CONDITIONALS)*/
let num = 7;
if (num % 2 === 0) {
console.log("EVEN");
}
if (num > 0) {
console.log("POSITIVE");
}
//POSITIVE
/*We find that the output is POSITIVE, even though 7 is odd and so
nothing should be printed. This code doesn't work as desired because
we only want to test for positivity when we already know that the
number is even. We can enable this behavior by putting the second
conditional inside the first.*/
//USING NESTED CONDITIONALS:
let num = 7;
if (num % 2 === 0) {
console.log("EVEN");
if (num > 0) {
console.log("POSITIVE");
}
}
/*Notice that when we put one conditional inside another, the body of
the nested conditional is indented by two tabs rather than one. This
convention provides an easy, visual way to determine which code is
part of which conditional.*/