Example: Program to Guess a Number
Output
Guess a number from 1 to 10: 1 Guess a number from 1 to 10: 8 Guess a number from 1 to 10: 5 Guess a number from 1 to 10: 4 You guessed the correct number.
Note: You will get different output values each time you run the program because each time a different number is generated.
In the above program, the guessNumber() function is created where a random number from 1 to 10 is generated using Math.random() function.
To learn more about how to generate a random number, visit JavaScript Generate Random Number.
- The user is prompted to guess a number from 1 to 10.
- The
parseInt()converts the numeric string value to an integer value. - The
whileloop is used to take input from the user until the user guesses the correct answer. - The
if...elsestatement is used to check the condition. The equal to==operator is used to check if the guess was correct.if(number == random)
To learn more about the comparison operators, visit JavaScript Comparison Operator.