# How to code a Javascript Random Number Generator

·2 mins Generating random numbers in JavaScript is easy once you understand how the built-in function to do this works but a lot of developers tend to write repetitive code rather than creating their own random number function which can be re-used.

So in this article I am going to show you how to write your own JavaScript random number generator function which will generate random numbers in a range that you specify.

Watch the video tutorial here.

## Using Math.random() #

So the basics of generating random numbers in JavaScript is to use the `Math.random()` function which is something that is built-in to the JavaScript language.

A simple call to generate a random number might look this:

``````const number = Math.random();
console.log(number); // 0.2908743426757856
``````

If you run this in the browser you will see a long decimal (or floating point) number generator that is anywhere in between 0 and 1;

This isn’t the most useful if you want to be working with whole numbers so we can wrap this in a call to `Math.floor` to round it down after it has been multiplied by a certain number.

``````const number = Math.floor(Math.random() * 100);
console.log(number); // 33
``````

## Writing a re-usable function #

So now that we understand how to actually get a random number in JavaScript, how do we create a nice re-usable function that will generate a number in any range?

It’s simply a case of wrapping a call to `Math.random` in a function and providing an upper and lower limit for the range.

``````const generateRandomNumber = (from = 1, to = 100) => {
return Math.floor(Math.random() * (to - from + 1) + from);
};
``````

This function will generate a random number between a given range and will default to 1 and 100 as specified by the default function argument values.

Adding `+ 1` to the `to - from` calculation just ensures we’re getting the numbers in the range inclusive of the start and end range numbers.

Putting it all together we can generate an array of random numbers for our app code by calling the `generateRandomNumber` function several times.

``````const generateRandomNumber = (from = 50, to = 100) => {
return Math.floor(Math.random() * (to - from + 1) + from);
};

const randomNumbers = [];

for (let i = 0; i < 10; i++) {
randomNumbers.push(generateRandomNumber());
}

console.log(randomNumbers);
`````` Author
James Bubb
Hi i’m James, a web developer mainly working with JavaScript/TypeScript Angular and Node. Come say ‘Hi’ to me on Twitter, or check out some of my tutorials on YouTube.