Patpads
Patpads

Reputation: 3

stuck with Javascript infinite while loop

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

Answers (5)

Nabil Kadimi
Nabil Kadimi

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

go-oleg
go-oleg

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

mikedugan
mikedugan

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

Mike Christensen
Mike Christensen

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

Lee Meador
Lee Meador

Reputation: 12985

Use == instead of = in the while part.

Upvotes: 3

Related Questions