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 JavaScript Numbers The Math Object Random Number Challenge – Solution

Gabriel Pavel
Gabriel Pavel
617 Points

What am i doing wrong?

It seems that i always overthink the solution when it's simpler than that, what am i doing wrong?

// Collect input from a user
const answer = prompt('Can you write the correct number between one to nine?');

// Convert the input to a number
const yourNumber = parseInt(answer);
let message = '';

// Use Math.random() and the user's number to generate a random number
const rightNumber = Math.floor(Math.random() * 9) + 1;
  if (yourNumber === rightNumber) {
            message = 'Perfect! You guessed the right number!';
        } else if (yourNumber >= 1 && yourNumber <= 9) {
            message = `Wrong! The correct number was ${rightNumber}. Try again.`;
        } 
document.getElementById('message').innerHTML = message;

// Create a message displaying the random number

console.log(`Your number was ${yourNumber}!`);
console.log(`The correct number was ${rightNumber}!`);

1 Answer

Steven Parker
Steven Parker
231,109 Points

I don't see any obvious errors in this code. But you did not show the HTML that goes with this, and the program relies on updating an element with the id of "message". If the HTML doesn't define that element there will be an error.

But what this program does is different from what the challenge asked for. This code implements a number guessing game, but the challenge was just to create a program that picks and displays a random number.   :see_no_evil: