0

Please keep in mind that I'm a beginner with JavaScript.

I am experiencing some problems with a simple code in JavaScript. What I am trying to accomplish is a While loop, that will continuously ask the user to "Enter name" unless the Prompt box is empty OR the user selects cancel.

When I hit cancel or type in nothing and hit OK, the while loop still executes, and from the specified conditions I can't figure out why.

I also thought this may be because it is not recognizing what the var "userInput" is so I tried declaring it outside the loop.

Here is my code. Any help is appreciated.

var userInput;

while(userInput =! null || userInput != ""){
userInput = prompt("Enter name","");
var array = [userInput];
document.write(array.sort() + "<br />")

}
Zzgooloo
  • 39
  • 6
  • You are assigning the variable `array` on every entry. You need to put the array outside the while loop and simply push new values to it. – Shane Jul 20 '16 at 22:16
  • Should the || not be &&? while(userInput =! null && userInput != ""){ ... – Nitin Jul 20 '16 at 22:18
  • Ok, understood about the array, why is the while-loop still executing on null and " " though? – Zzgooloo Jul 20 '16 at 22:19
  • Nitin, well I want to make sure that whether the user enters blank " " OR they cancel for the loop to stop execution. I believe I would need || for that. – Zzgooloo Jul 20 '16 at 22:19
  • Do not use document.write and you are redefining the array on every iteration so you are sorting one item... – epascarello Jul 20 '16 at 22:20
  • espascarello, I want the names to be printed to the screen. Can you tell me what to use instead? and why not to use document.write? Thanks I fixed the array and defined it outside the loop – Zzgooloo Jul 20 '16 at 22:21
  • Thanks for all the input, but none of these explain why the loop still executes given my specified conditions. Any ideas? – Zzgooloo Jul 20 '16 at 22:24
  • @Quentin answer was correct, it's due to the `||` condition. Only one of them have to be true for the condition to be true. If the value is `""`, then `"" != null` is `true`. If the value was `null` then `null != ""` will be true. – Spencer Wieczorek Jul 20 '16 at 22:26
  • @SpencerWieczorek Can you explain why? From what I have learned so far && is used when both conditions must be true and || will return true if either condition is. And that is what I am trying to accomplish here. Whether the user types nothing OR hits cancel (Which i believe returns null) – Zzgooloo Jul 20 '16 at 22:28
  • You have a typo: `=!` should be `!=`. – Barmar Jul 20 '16 at 22:30
  • @Mozar Remember, the condition in `while` tells it when to repeat, not when to stop. If the user types nothing, `userInput != null` will be true, so it repeats. – Barmar Jul 20 '16 at 22:31
  • And if they hit cancel, `userInput != ""` will be true, so it repeats. – Barmar Jul 20 '16 at 22:32
  • @Barmar I understand.. Thank you – Zzgooloo Jul 20 '16 at 22:36

0 Answers0