Categories
JavaScript Answers

How to Generate Random Numbers with JavaScript?

Spread the love

The JavaScript standard library has a Math object, which has a random method to generate random numbers between 0 and 1. It takes no arguments.

By itself, it’s of limited use since it can only generate numbers between 0 and 1, but we can easily use it to generate random numbers in any range.

For example, if we want to generate a number between a minimum and a maximum number, we can write the following code:

const min = 1;
const max = 100;
const num = Math.random() * (max - min) + min;
console.log(num);

In the code above, we have a formula that has the min number as the minimum number, then we add Math.random() * (max — min) to min. max-min would be positive since max is bigger than min and Math.random() returns a number between 0 and 1 so it would either be 0 or positive.

If max is the same as min, then we get min as the result of num, which is the lowest number we’ll accept, and if Math.random() is 0 we get the same thing.

If Math.random() is 1, we get max — min + min which is the same as max. This means that the formula would never be outside of the number range between min and max, which is what we want. The formula above will get us any floating-point number. If want integer results only, we can write:

let min = 1;
let max = 10;
min = Math.ceil(min);
max = Math.floor(max);
const num = Math.floor(Math.random() * (max - min)) + min;
console.log(num);

In the code above, we rounded down our result to the nearest integer with the Math.floor(Math.random() * (max — min)) method call. This makes sure the result generated would be between 1 inclusive and 10 exclusive.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *