Search code examples
javascriptfunctionloopsif-statementreturn

Why does an if function doesn't run prompt again with numbers?


The last function is supposed to run again when user does not write any input and presses enter. The first and the second functions work fine : without any valid input, the function runs the right prompt. What is it that I'm missing? Is it because the last if-statements refer to intengers?

<!DOCTYPE html>
<html lang="en">
    <head>
    <meta name="author" content="Yann">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Äventyret</title>
    </head>
<html>
<head>
<script src="spel8.js">
</script>
</head>
<body>
</body> 
</html>

function firstQuestion(){
    var string = prompt("Welcome to the port!\nDo you want to come on board?").toLowerCase();

    if (string === "yes"){
        alert("Interesting!");
        secondQuestion();
        return;
    }
    else if (string === "no"){
        alert("Goodbye!");
        return;
    }
    else {
        alert("Answer with \"yes\" or \"no\".");
    }
    firstQuestion();  
}

firstQuestion();


function secondQuestion() {
  var str = prompt("Have you ever sailed?").toLowerCase();

    if (str === "yes") {
        alert("Great!\nI still have a question for you.");
        thirdQuestion();
        return;
    }
    else if (str === "no"){
        alert("I need experienced sailors!");
        return;
    }
   secondQuestion(); 
}

function thirdQuestion () {
    var string = prompt("How old are you?");

    if (string < 14){
        alert("You're too young!\nGo home!");
        return;
    }
    else if (string >= 14){
        alert("Welcome on board!");
        return;
    }
    thirdQuestion();
}

Solution

  • There's no chance in the third function for the self-call to thirdQuestion to be hit because the if and else if conditions cover all scenarios. If string < 14 is not true, then its exact opposite string >= 14 will always be true.

    I think you want something more like this:

    function thirdQuestion () {
        var string = prompt("How old are you?");
        var age = parseFloat(string);
    
        if (!string || isNaN(age)) {
            return thirdQuestion();
        }
    
        if (string < 14) {
            alert("You're too young!\nGo home!");
            return;
        }
    
        alert("Welcome on board!");
    }
    

    Notice that we convert the input string to a number with parseFloat; JavaScript can compare strings and numbers, but you might get unexpected results. The code also checks if the string could be successfully parsed as a number with isNaN (is not a number).