Nested Conditionals with Else

for CSCI E3, Harvard University author(s): Larry Bouthillier

by DustyWhite

HTML

Week 4 BETTER EXAMPLE: <b>Be sure to open your console to see the output of this code.</b>
<ol>
    <li>There are several things to notice here. The first <i>if</i> statement runs from line 6 to line 16, with its <i>else</i> section from line 16-19.</li>
     <li>
         Inside the first <i>if</i> block, only if hasBananas is true, we prompt the user for a number (line 8) and then have a new conditional on lines 11-15 to handle that case.   </li>
    <li>You can nest like this as deeply as you need to. Beware to keep your code neat, your indentation consistent, your braces matching, and use comments.  It's easy to get mixed up - a misplaced brace will break your code and can be very hard to locate - so good code hygiene is important! </li>
</ol>

CSS

ol li {padding-bottom: 1em;}

JavaScript

"use strict"

var hasBananas = confirm("Do you have bananas? ([OK] for yes, [Cancel] for no)");

// here's the first conditional to see if there are bananas
if (hasBananas){
    // if true, then we'll ask for the number of bananas
    var numBananas = prompt("How many bananas");

    // plural or singular?
    if (numBananas == 1){
        console.log("You have "+ "a" "+" banana");       
    }else{
        console.log("You have "+ numBananas +" bananas");
    } 
}else{
     //hasBananas was false
    console.log("I'm sorry that you have no bananas!")
} 
//this code runs no matter what
console.log("Whether or not you had bananas, have a good day!");