I want to end the while loop when user clicks cancel in the confirm box

Viewed 32
        let age = Number(prompt('Enter your age'))
        if (age <= 0) {
            alert('Enter a valid age')
            console.error('Enter a valid age');
        }
        if (age < 18) {
            alert('You cannot drive')
        }
        else if (age >= 18) {
            alert('Yes you can drive')
        }

        let askAgain = confirm('Do you want to see thr prompt again?')

        while (askAgain == true) {
            let age = Number(prompt('Enter your age'))
            if (age <= 0) {
                alert('Enter a valid age')
                console.error('Enter a valid age');
            }
            else if (age >= 18) {
                alert('Yes you can drive')
            }
            if (age < 18) {
                alert('You cannot drive')
            }
            let askAgain = confirm('Do you want to see thr prompt again?')
        }

I want to make the confirm box go away if the user selects cancel. It works fine the first time but if I select ok first and the while loop executes and then It keeps on showing the confirm box even if I select cancel.

1 Answers

You have declared askAgain variable twice - first outside the while loop and then again inside the loop.

Just remove the 'let' keyword present in front of askAgain (which is present inside of while loop). This will fix the issue.

Related