Write a JavaScript Program to Guess a Random Number

As a JavaScript programmer, you may come across scenarios where you need to generate a random number and guess it.

In this tutorial, we will walk through a simple JavaScript program that generates a random number and allows the user to guess it.

To begin, we will use the Math.random() method to generate a random number between 0 and 1.

To get a random number between 1 and 10, we can multiply the result by 10 and then use the Math.floor() method to round it down to the nearest whole number.

Here’s the code to generate a random number between 1 and 10:

let randomNumber = Math.floor(Math.random() * 10) + 1;

Now that we have a random number, we can ask the user to guess it. We will use the prompt() method to get input from the user.

We will then use an if statement to check if the user’s guess matches the random number.

If the user guesses correctly, we will display a message to congratulate them.

If the user guesses incorrectly, we will display a message to let them know their guess was incorrect and ask them to try again.

Here’s the complete code for the program:

let randomNumber = Math.floor(Math.random() * 10) + 1;
let guess = prompt("Guess a number between 1 and 10");

if (guess == randomNumber) {
alert("Congratulations! You guessed the correct number.");
} else {
alert("Sorry, your guess was incorrect. Please try again.");
}

In the above code, we first generate a random number between 1 and 10 using the Math.random() and Math.floor() methods.

We then use the prompt() method to get the user’s guess and store it in a variable called guess.

We then use an if statement to check if the user’s guess matches the random number.

If the guess is correct, we display a message to congratulate the user.

If the guess is incorrect, we display a message to let them know their guess was incorrect and ask them to try again.

In conclusion, generating a random number and guessing it using JavaScript is a simple task that can be accomplished using the Math.random(), Math.floor(), and prompt() methods.