# Generate a random number or integer in a range with JavaScript

JavaScript's `Math.random()` is handy for generating random numbers between 0 and 1. If you need a random number in a different range, you'll need to use some simple math to map the random number to the desired range.

## Random number in a range

The simplest use case you'll come across is to generate a random number in a specified range. All you need to do is multiply the result of `Math.random()` by the difference between the maximum and minimum values, and then add the minimum value.

```const randomNumberInRange = (min, max) => Math.random() * (max - min) + min;

randomNumberInRange(2, 10); // 6.0211363285087005```

## Random integer in a range

Subsequently, generating a random integer is very similar, except for an additional step at the end. You need to use `Math.floor()` to round the result down to the nearest integer.

```const randomIntegerInRange = (min, max) =>
Math.floor(Math.random() * (max - min + 1)) + min;

randomIntegerInRange(0, 5); // 2```

## Gaussian random numbers

Finally, if you need to generate Gaussian (normally distributed) random numbers, you can use the Box-Muller transform to generate random numbers with a Gaussian distribution.

```const randomGauss = () => {
const theta = 2 * Math.PI * Math.random();
const rho = Math.sqrt(-2 * Math.log(1 - Math.random()));
return (rho * Math.cos(theta)) / 10.0 + 0.5;
};

randomGauss(); // 0.5```

## More like this

• Collection · 6 snippets

### JavaScript Random Value Generators

Quickly and easily generate random integers, strings, booleans, arrays and hex color codes using JavaScript.

• JavaScript ·

### Generate a JavaScript array of random integers in a given range

Combining `Math.random()` and a few simple math operations, you can generate an array of random integers in a specified range.

• JavaScript ·

### Clamp or map a number to a range in JavaScript

Clamping and mapping a number to a range are two common and easily confused operations. Learn how to perform each in JavaScript.

• JavaScript ·

### Generate a random hex color code in JavaScript

Learn how to generate a random hexadecimal color code with a few lines of JavaScript.

Start typing a keyphrase to see matching snippets.