Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Why do I get into an infinite loop?

Hey guys, I am building a number guessing game. In this game, you can add an infinite amount of players. I am trying to make it so, that it gives an alert if the guess of the player is not a number. However for some reason I get into an infinite loop, and i do not necessarily know why.

Here is the code snippet that causes the loop:

var guessPlayer = []; //Array that stores the guesses of each player 
var playerNums = 3; //Amount of players 
var players = []; //Array that stores names of every player

  for (var i = 0; i < playerNums; i += 1 ){
    do{
      guessPlayer.push(parseInt(prompt(players[i] + " What do you think?")));
      if(isNaN(guessPlayer[i])){
        alert("Sorry, this is not a number");
      }
    } while(isNaN(guessPlayer[i]))
  }

For those interested. I thought the problem was perhaps in the index number of the array that causes the infinite loop. when the player has entered something which is NaN, that value stays in the array. I thought that the loop is caused by the fact that it constantly uses the index number with the value NaN over and over again. To bypass that issue I have also tried the following code, which unfortunately does not work either!! I am a complete noob, help...

function guessNumber(){
  for (var i = 0; i < playerNums; i += 1 ){
  do{
      notValid = false;
      guessPlayer.push(parseInt(prompt(players[i] + " What do you think?")));
      if(isNaN(guessPlayer[i])){
        alert("Sorry, this is not a number");
        guessPlayer.pop();
        notValid = true;
      }
    } while( notValid = true )
  }
}

1 Answer

in your for loop i goes up to playerNums, but playerNums is not defined. it is only declared.

playerNums is declared in piece of code above. I just copied and pasted some of the variable declarations. There is a lot more code in between haha. That is my fault, sorry.

But suppose that playerNums is declared, would you know why there is an infinite loop?