Search code examples
javascriptif-statementprompt

How do I "restart" if statement if a condition is met?


I'm very new to javascript. I wanted to make a quick program that generates the youngest age possible a person is able to date given their age, using the formula my dad taught me. In my code I have a condition where if my var (dateage) isn't a number, the user is asked to please enter in a number. I want the program to then re-ask the variable assignment prompt until a number is given.

var dateage = prompt("How old are you?");

if(dateage >= 14){
    dateage = dateage/2 + 7;
    alert("The youngest you can date is " + dateage)
} else if(isNaN(dateage)){
   alert("Please enter in a number");
} else
   alert("You're too young to date.");

You can see that if dateage isn't a number, the user is alerted. At that point I want the prompt to appear again asking the user for their age. How can I do this?


Solution

  • Put it in a function so you can re-invoke

    function checkAge() {
        var dateage = prompt("How old are you?");
    
        if(dateage >= 14){
            dateage = dateage/2 + 7;
            alert("The youngest you can date is " + dateage)
        } else if(isNaN(dateage)){
           if (confirm("Please enter in a number")) checkAge();
        } else
           alert("You're too young to date.");
    }
    checkAge();
    

    I used a confirm for the re-check because this means you can more easily escape from an infinite loop situation. If you don't want to pollute the namespace, you can write this as a named IIFE, and if you don't want to carry the stack over, you can invoke through a setTimeout.