JavaScript(JS) JS guess a random number
To guess a random number in JavaScript/JS, you can use the Math.random()
method to generate a random number between 0 and 1, and then multiply it by a range and add a starting value to get a random number within that range.
Here's an example code snippet that demonstrates how to generate a random number between 1 and 100:
const randomNumber = Math.floor(Math.random() * 100) + 1;
In this example, Math.random()
generates a random number between 0 (inclusive) and 1 (exclusive), and then we multiply it by 100 to get a random number between 0 (inclusive) and 100 (exclusive). We then use Math.floor()
to round down to the nearest integer, and add 1 to shift the range to be between 1 (inclusive) and 100 (inclusive).
To create a game where the user can guess a random number, you could use this random number as the target number, and then prompt the user to enter a guess and compare it to the target number using conditional statements.
Here's an example code snippet that demonstrates a simple guessing game:
// Generate a random number between 1 and 100 const targetNumber = Math.floor(Math.random() * 100) + 1; // Prompt the user to enter a guess const userGuess = parseInt(prompt("Guess a number between 1 and 100")); // Compare the user's guess to the target number and provide feedback if (userGuess === targetNumber) { console.log("Congratulations! You guessed the correct number."); } else if (userGuess < targetNumber) { console.log("Your guess is too low. Try again."); } else { console.log("Your guess is too high. Try again."); }
In this example, we first generate a random number between 1 and 100 and store it in the targetNumber
variable. We then prompt the user to enter a guess using the prompt()
function, which returns a string that we parse as an integer using parseInt()
. We then compare the user's guess to the targetNumber
using conditional statements and provide feedback based on whether the guess is too high or too low. If the guess is correct, we congratulate the user.