Reputation: 3
My apologies for the n00b question, I've tried looking through infinite loop related issues but they're way more complex:
var replay = 1;
while (replay = 1) {
replay = prompt("Yes(1) or No(0) ?");
}
How come this is an infinite loop?
I thought this while loop would only continue iterating while the replay variable has a value of 1.
However it doesn't stop even when user input is 0, or anything else for that matter.
Thanks in advance for any of your input!
Upvotes: 0
Views: 2751
Reputation: 10394
You are assigning not checking in (replay = 1)
You need double equal signs ==
, or better yet triple equal signs ===
which will also check the equality in types of the operands.
Besides, your code can be changed to this (preview: http://jsfiddle.net/nabil_kadimi/RfdA5/):
var replay;
while ((replay = window.prompt("Yes(1) or No(0) ?")) === '1') {
/* player wants to replay */;
}
Or even better (preview: http://jsfiddle.net/nabil_kadimi/pdV4M/):
var replay;
while (replay = window.confirm("Replay?")) {
/* player wants to replay */;
}
Upvotes: 1
Reputation: 19480
You want to use the ===
comparison operator instead of the =
assignment operator in the while loop.
Also, since prompt
returns a string
, you should compare against a string
:
var replay = "1";
while (replay === "1") {
replay = prompt("Yes(1) or No(0) ?");
}
Upvotes: 0
Reputation: 2393
You need to use == (equality) instead of = (assignment) in your while loop
while(replay == 1) {
//code
}
JavaScript is doing what it is supposed to. You are reassigning the value of 1 to replay every time the loop iterates. You really want to check if replay is equal to one before proceeding.
Upvotes: 1
Reputation: 91600
You're doing an assignment instead of a comparison.
Change:
while (replay = 1) { // Will always have a value of 1
to:
while (replay == 1) { // Will have a value of true or false
Upvotes: 4