A number generated by a process, whose outcome is unpredictable is called Random Number. In JavaScript, this can be achieved by using Math.random() function. This article describes how to generate a random number using JavaScript.
Method 1: Using Math.random() function: The Math.random() function is used to return a floating-point pseudo-random number between range [0,1), 0 (inclusive), and 1 (exclusive). This random number can then be scaled according to the desired range.
Syntax:
Math.random();
Example 1: This example generates an integer random number between 1(min) and 5(max).
JavaScript
function randomNumber(min, max) {
return Math.random() * (max - min) + min;
}
console.log( "Random Number between 1 and 5: " )
console.log( randomNumber(1, 5) );
|
Output:
Random Number between 1 and 5: 1.0573617826058959
Method 2: Using Math.floor() function: The Math.floor() function in JavaScript is used to round off the number passed as a parameter to its nearest integer in the Downward direction of rounding i.e. towards the lesser value.
Syntax:
Math.floor(value)
Example 1: This example generates a random integer number between 1(min) and 100(max).
JavaScript
function randomNumber(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
console.log( "Random Number between 1 and 100: " )
console.log( randomNumber(1, 100) );
|
Output:
Random Number between 1 and 100: 87
Example 2: This example generates a random whole number between 1(min) and 10(max) both inclusive.
JavaScript
function randomNumber(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log( "Random Number between 1 and 10: " )
console.log( randomNumber(1, 10) );
|
Output:
Random Number between 1 and 10: 3