JavaScript JavaScript Numbers The Math Object Random Number Challenge – Solution

I get this // 359 is a random number between 450 and 650.

2 Answers

Tai Jun Jie
.a{fill-rule:evenodd;}techdegree seal-36
Tai Jun Jie
Full Stack JavaScript Techdegree Graduate 23,907 Points

Hello Jason,

const highNumber = parseInt(inputHigh);
const randomNumber = Math.floor(Math.random() * highNumber + 1);

This will only generate a random number from 1 to your highNumber.

In order to generate a random number between the low number and high number, you can consider the following code:

const randomNumber = Math.floor(Math.random() * (highNumber - lowNumber + 1)) + lowNumber;

In order to change your range from (1 , highNumber) to (lowNumber , highNumber) , you need to add lowNumber to your randomNumber at the end. However, that will increase your range to (lowNumber , highNumber + lowNumber) . Hence, you have to minus away the ow number inside the Math.floor expression. Hope this helps

const randomNumber = Math.floor(Math.random() * highNumber + 1);

Seems like the variable is incorrect. based on video tutorial the + 1 go outside the parenthesis :

Math.floor( Math.random() * 6) + 1;

here my solution:

let inputHigh = parseInt(prompt('Enter a number 1 thru 6.')); let randomNumber = Math.floor( Math.random() * 6) + 1; //Math.random() will generate a random number //ParseInt will convert user input into an integer number //and it will prevent me from creating an extra variable //also I made use of if statements to combine what I already learned with JS.

if(inputHigh === randomNumber) { console.log("you gess correct"); } else { console.log(the correct nnnumber ${randomNumber} || your input ${inputHigh}); }