One of the JavaScript data types is a number. In our previous tutorials, we covered methods used for handling them.
In this tutorial, you will learn all about the JavaScript random method in more detail. We will explain how you can generate random numbers in JavaScript, providing some simple code snippets you can use yourself.
Contents
JavaScript Random: Main Tips
- When returning a random number from 0 (inclusive) to 1 (exclusive), we use Math.random JavaScript method.
- It is a very good idea to create a proper function for Math.random JavaScript method to be used for all random integer purposes.
- Ability to generate random numbers is especially handy when creating games.
What is JS random?
By default, JavaScript Math.random()
method will be returning a number higher than 0 (inclusive) and lower than 1 (exclusive):
To bring back random integers, we can use Math.random()
with Math.floor()
:
Examples
As we have shown in the examples above, creating a proper function for random
to be used for all JavaScript random integer purposes is rather useful. Let's see a few more random function JavaScript examples to make sure we covered everything.
The random function JavaScript example below shows a function which always brings back a random number from min
(included) to max
(excluded):
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min) ) + min;
}
Now, the next code example shows a function which always brings back a random number from min
to max
(both included this time):
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1) ) + min;
}
JavaScript Random: Summary
- You can use Math.random method to return a random number from 0 (inclusive) to 1 (exclusive).
- Using this method, you can create a proper function using variables to return all JavaScript random integers.
- If you are into creating games, the ability to get random numbers automatically might prove to be extremely useful for you.