Create n length random number in JavaScript

We can generate fixed length random number using Math.random() function. Math.random can generate number between 0 to 1. We can use this to generate any length random number.

function randomNumber(length) {
    return Math.floor(Math.pow(10, length-1) + Math.random() * (Math.pow(10, length) - Math.pow(10, length-1) - 1));

Above function can be use to generate any length of random number.

randomNumber(5) // 59478
randomNumber(6) // 458451

Generate random number within a range

To generate a random number between two specific numbers (min included, max excluded)

function randomNumber(min, max) { 
    return Math.floor(Math.random() * (max - min) + min);

In the above code, we used (max - min) + min to avoid cases where the max number is less than the min number. The Math.floor() is used to round off the number.

randomNumber(100, 500) //440
randomNumber(1000, 5000) // 3983

Leave a Reply