- Instant help with your JavaScript coding problems

Generate a random number in a range with JavaScript

Question:
How to generate a random number in a range with JavaScript?
Answer:
function getRandumNumber(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
}

console.log(getRandumNumber(1, 10)); 
Description:

To generate a random integer number between 2 values, including both the min and max you can use the Math.random function with some extra mathematical operations.  

The Math.random() function returns a floating-point, pseudo-random number in the range 0 to less than 1 (inclusive of 0, but not 1) with approximately uniform distribution over that range. But in real life, you don't usually want to generate a floating-point number between 0 and 1. That's why some extra operation is required with minimum and maximum values of the desired interval.

Note: Math.random() does not provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the window.crypto.getRandomValues() method.

Share "How to generate a random number in a range with JavaScript?"