1

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

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

2
  • 1
    while (j = 1) is the issue I think change it to J == 1 Commented Dec 21, 2022 at 0:24
  • For any viewers, this didn't work :( Commented Dec 21, 2022 at 0:31

1 Answer 1

1

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++;
}
Sign up to request clarification or add additional context in comments.

2 Comments

It worked! Waiting for time to mark your answer
You guys on stack overflow are fast!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.