DEV Community

Cover image for Random Number Generation in JS
Krishna Dhakal
Krishna Dhakal

Posted on

Random Number Generation in JS

Here we will be generating the random number of 9 digits using JS.

function getRandom(length) {

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

}
getRandom(9)
Enter fullscreen mode Exit fullscreen mode

Output:

234664534
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
nastyox1 profile image
nastyox •

Very cool approach! I noticed that you disallowed leading zeros, and I think that's a good choice because the function returns a number, not a string, and leading zeros would be ignored anyway. The only time I think a zero might be expected as the first digit would be when calling getRandom(1). You might expect 0 to be a possible result then, but it's not currently.

Love the function; very creative.

Collapse
 
chauchausoup profile image
Krishna Dhakal •

Hello friends its my first blog in this platform. I was trying to go with netlify for static site generation but I thought dev community is benificial for me to learn and communicate with fellow dev friends.

Collapse
 
b0yblake profile image
Lichhuun •

Yes, well come you! You can let the func more useful by adding the condition to passing the autotest.