Tutorials Tonight's Logo
Follow Us

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.

const random = Math.random();
console.log(random);

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.

const randomFrom0To10 = Math.random() * 10;
const floor = Math.floor(randomFrom0To10);
const numberFrom1To10 = floor + 1; // desired output
console.log(randomFrom0To10);
console.log(floor);
console.log(numberFrom1To10);

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.

function numberInRange(max, min) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}
console.log(numberInRange(15, 50));

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).

function randomColor() {
  let color = "#";
  for (let i = 0; i < 6; i++) {
    color += Math.floor(Math.random() * 10);
  }
  console.log(color);
}
randomColor();
▶ Try It

More Learning

Want to learn more about programming and web development? We have a few recommendations for you.


Follow Us

Copyright © Tutorials Tonight. All Rights Are Reserved.