Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Break out of while loop that has an array inside

Want to let the user make an array until they press cancel on the prompt
But the nested if statement won’t trigger and break the while loop.

The goal of the program is to show the first ten items in the array with the message
‘Only the first ten guests will be recorded’
This is part of my course which is why I am letting the user input as much as they like
and then reducing it to 10 after.

let guests = []
i = 1
j = 1

while (j = 1) {
    input = guests.push(prompt('Enter Guest' + i + '(press cancel to stop)'))
    i++

    if(input === null) {
        j++
        //break;
    }
}

if (guests.length > 10) {
    console.log('Only the first ten guests will be recorded')

    while (guests.length > 10) {
        guests.pop()
    }
}

console.log(guests)

If I remove the if() brackets the program stops after the user inputs one array item

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

And if I try break;
it stops after the user types in 1 array item.

I have also tried adding

    else {
        continue;
    }

but to no avail

>Solution :

Store the result of prompt to test for null (instead of comparing the return value of Array#push).

while (true) {
    input = prompt('Enter Guest' + i + '(press cancel to stop)');
    if(input === null) break;
    guests.push(input);
    i++;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading