Pete Junior
Pete Junior

Reputation: 25

Function that accepts two numbers and returns a random number between the two numbers. (JavaScript)

Been learning JavaScript for a few weeks now, and I am trying to write a function that prompts the user for 2 numbers and the generate a random number between them. I wrote this code,

function randomInt(min,max) {

var min = prompt( "Enter a number." );
var max = prompt( "Enter another number." );
var randNum = Math.floor(Math.random() * (max - min + 1)) + min;

return randNum;

}
alert(randomInt());

It does prompt me for the numbers but it generates a random number not a number between the two that I've entered. Like I enter 5 and 20 and it returns 31 or 2 but when tried,

var min = 5;
var max = 20;

It works, actually gives me a number between 5 and 20, not sure why though. It seems like a simple task but just stumped.

Upvotes: 1

Views: 943

Answers (1)

Pointy
Pointy

Reputation: 413916

The prompt() function returns strings, not numbers. You can force the values to be interpreted as numbers with the unary + operator:

    var min = +prompt("Enter a number.");
    var max = +prompt( "Enter another number." );

Without that, the outer + operator will preferentially perform a string concatenation operation because the right-hand operand (min) is a string. That is, in this expression:

    Math.floor(Math.random() * (max - min + 1)) + min

The - operator in max - min will cause that to be done properly as a numeric subtraction. However, the outer + by which the minimum value is added back to the random number will perform a string concatenation and not a numeric addition if min is a string. Thus you'll end up with a random integer between 0 and the implied range, concatenated onto the minimum value (as a string).

Upvotes: 1

Related Questions