Creating Random number in JavaScript

Hello All

Have you ever needed to create random number in JavaScript?


In C#, creating random number is simple and provides multiple options. Random class is used for the same, it’s Next method used to create random number. It also takes min and max value as parameter to create a random number in a range.

In Javascript it is more simple🙂. Let’s see that

Math.random is used to create a random number. But it returns a decimal numal number between between 0 (including) to 1(excluding). Let’s see that

function displayRandom()

It will create different number each time. So if you want to create a random number say upto 10000 then you can get it by simply writing

var randomnumber = Math.random() * 10000;

Pretty simple Right!!

But it will always create a number less than 10000 (till 9999.999..) and if you take the integer part then the max value you will get 9999. But what if want inclusive of 10000?

Then you can leverage the other method Math.ceil which generates the ceiling number as





For all you will get 7. So if you write the original method as

function displayRandom()

You will get the number between 0 to 10000 both inclusive. You can also use Math.floor or Math.abs to have your own logic for getting random number in a range.

This is small post but I found it bit interesting and useful sometime.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s