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

Can't figure out what is wrong with my code.

var answerNo = 0;
var correctAnswer = 0;
var gameEnd = false;

function diceRoll (){
  return Math.floor((Math.random() * 12) + 1);
};

if (answerNo === 5){
  gameEnd = true;
  alert('You were correct ' + correctAnswer + ' times!');
} else if (!gameEnd){
  for (i = 0, i < 5, i++){
    var randomNumber = diceRoll();
    var guess = prompt('Guess a number.');
    answerNo++;
    if (parseInt(guess) === randomNumber){
      correctAnswer++;
    }
  }
}

2 Answers

By looking at your code, I think you have forgot to declare the i variable inside the for loop and add a semi colon between the initialiser, the condition and the incrementer.

var answerNo = 0;
var correctAnswer = 0;
var gameEnd = false;

function diceRoll (){
  return Math.floor((Math.random() * 12) + 1);
};

if (answerNo === 5){
  gameEnd = true;
  alert('You were correct ' + correctAnswer + ' times!');
} else if (!gameEnd){
  for (let i = 0; i < 5; i++){
    var randomNumber = diceRoll();
    var guess = prompt('Guess a number.');
    answerNo++;
    if (parseInt(guess) === randomNumber){
      correctAnswer++;
    }
  }
}

Thanks for the response, I've figured it out and changed a bit later on.

var score = 0;
var gameEnd = false;
var numbers = [];

function diceRoll() {
  return Math.floor(( Math.random() * 6) +1);
}

if (!gameEnd) {

  for (var i=0; i<6; i++) {

    var randomNumber = diceRoll();
    var guess = prompt('Pick a number!');

    numbers.push(randomNumber);

    if (parseInt(guess) === randomNumber) {
      alert("That's correct! Let's roll again!");
      score++;
    } else {
      alert("Wrong! Let's roll again!");
    }

  }

}

alert(numbers.toString() + '\n' + 'You were correct ' + score + ' times!');

javascript has it's qerks, I thought learning PHP would make learning javascript easier but I guessed wrong :)