In the initial loop, if i choose "y" why does it still loop over again and not move onto the next if statement?

Viewed 16

please use JavaScript conditional statements and at least one loop to write a program that satisfies each the following conditions:

If the user tries to get a beverage without placing their cup on the tray, display “Please place your cup on the tray.” If it is the custom refillable cup, display “Custom Refillable cup: Please make your selection.” If it is the custom non-refillable cup AND it is the first time using it, display “Custom Non-Refillable cup: You have one fill remaining; Please make your selection.” If it is the custom non-refillable cup AND it is NOT the first time using it, display “Custom Non-Refillable cup: You have zero fills remaining; Please leave.” If it is not either of the custom cups, display “This is an invalid cup; Please leave.”

    function myFunction() {  
       var haveCup = "n"
       while (haveCup === "n") {
           let haveCup = prompt("Have cup? y/n");

            if(haveCup === "y") {
                haveCup = "y";
            }
    
            else if(haveCup === "n") {
                haveCup = "n";
                alert("Please place cup on tray.");
            }
    
            else {
                alert('I said y or n you dummy!');
            }
    
    
        } 


        if (haveCup === "y") {
            let cup = prompt("What cup do you have? Custom Refillable Cup = crc or Custom Non-Refillable Cup = cnc");
            if (cup === "crc") {
                alert("Custom Refillable cup: Please make your selection.");
            }
            else if (cup === "cnc") {
                alert("Custom Non-Refillable cup: You have one fill remaining; Please make your selection."); 
            }
            else {
                alert("This is an invalid cup. Please leave.");
              }
            }

        let refill = prompt("Would you like a refill? y/n");
        if (refill === "y") {
            cupRefill = prompt("What is your cup type? cnc/crc");
            if (cupRefill === "cnc") {
                alert("Custom Non-Refillable cup: You have zero fills remaining; Please leave.")
            }
            else if (cupRefill === "crc") {
                alert("Here is your drink. Enjoy!")
            }
            else {
                alert("This is an invalid cup. Please leave.")
            }
        }
    }
1 Answers

Try this :

while (haveCup === "n") {
        haveCup = prompt("Have cup? y/n");

// remove let keyword as it creates a new local variable haveCup

Related