Guess Random Number in JavaScript

This is a preview lesson
Register or sign in to take this lesson.

This tutorial shows how to guess a random number in JavaScript. In JavaScript, we use in-built Math.random() and Math.floor() to generate a random integer number and if…else condition to check if a given guess number is correct or not.

Example 1: Guess a Random Number Generated by JavaScript

// program to guess a number generated by a program

function guessNumber(n) {

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

    if(n == random) {
        return 'You guessed the correct number.'
    }
    else{
        return 'You guessed the wrong number.'
    }

  }

console.log(guessNumber(1))

Output:

You guessed the wrong number.