JS Example for Beginners: JavaScript Program to Guess a Random Number

Hits: 41

(JavaScript programming Example for Beginners)

JavaScript Program to Guess a Random Number

In this example, you will learn to write a JavaScript program where the user has to guess a number generated by a program.


Example: Program to Guess a Number

// program where the user has to guess a number generated by a program

function guessNumber() {

    // generating a random integer from 1 to 10
    let random = Math.floor(Math.random() * 10) + 1;

    // take input from the user
    let number = parseInt(prompt('Guess a number from 1 to 10: '));

    // take the input until the guess is correct
    while(number !== random) {
        number = parseInt(prompt('Guess a number from 1 to 10: '));
    }

    // check if the guess is correct
    if(number == random) {
        console.log('You guessed the correct number.');
    }

  }

// call the function
guessNumber();

 

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.

 

JS Example for Beginners: JavaScript Program to Guess a Random Number

Sign up to get end-to-end “Learn By Coding” example.



Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.