tutorialstonight logo
A Platform To Learn To Code

How to create a random number in javascript?

Creating a random number in Javascript

To create a random number in javascript use Math.random() built-in function. It returns a floating-point random number between 0 (inclusive) and 1 (exclusive). This number behaves like a seed, it can be scaled to our desired scale.


Create a random number between 1 and 10

Let's us now scale the random number to get number as we desire. To get a number up to 'n' just multiply the output of Math.random() to 'n'.

Since returned number from Math.random() is from 0-1 so when the output is multiplied with 'n' then the number will range from 0 to 'n' (not inclusive).

Now add 1 to the number and range becomes 1 to 'n+1' (not inclusive). Since the number is float we use Math.floor() to get lower bound of the number, and now number ranges from 0 to n. put n = 10 to get the desired result.


Get a random number in range javascript

Using some manipulations you can also get a random number in the range.

You have the max and min of the range. Since

  • Math.random() range from [0, 1)
  • Math.random() * (max - min + 1) range from [0, max - min + 1)
  • Math.random() * (max - min + 1) + min range from [min, max + 1)
  • Math.floor(Math.random() * (max - min + 1)) range from [0, max]

So we can simply create a javascript function to create a number in a range.


Random Color Javascript

Generate a random color or a random background color for your webpage using the above concept.

Generate a random number from 0 to 9, six times and add these to a string starting with "#" symbol. It will be your random color to use (Hex color).


Try It