Spicy Yoghurt | Last updated: 17 September 2019 | JavaScript tutorial
Generate useful random numbers in JavaScript
Learn all about generating random numbers in JavaScript you can actually use. Get numbers between a certain range, generate random integer- and boolean values and learn about the use of seeds.
Generate a basic random number with Math.random()
In JavaScript, generating random numbers is done through the Math object. It contains many helpful mathematical functions and one of which is the random() function. This function generates a floating-point number between 0 and 1 (including 0, excluding 1) and can be used as the base for calculating other random values. You can access the Math object from anywhere in your code.
Here's an example of how to use the basic random() function on the Math object to generate a random decimal number:
Math.random();
//Possible output
0.8974465382241915
0.2958720891619725
0.006575835239084449
0.9456002830285726
As you can see, it just generates numbers between 0 and 1 and isn't very applicable in its current state.
The numbers generated by the random() function are just the start and need to be processed in other calculations to really make them useful. This way you can generate numbers within a certain range or meet other requirements.
Get a random number between two values
On their own, the results from the random() function aren't very useful, but they can be scaled to generate other types of random values.
Imagine you need a random number within a certain range, let's say somewhere between 0 and 10. The basic random() function won't go beyond 1 (it will never reach 1, to be precise), but by multiplying the result you can generate larger numbers.
In the following example random() is used to generate a random decimal number between a min- and max value (including min, excluding max).
function getRandomNumber(min, max) {
return Math.random() * (max - min) + min;
}
getRandomNumber(0, 10)
//Possible output
3.8690255118743275
0.15779814409071835
7.52113864188321
9.401215911876138
In the example, the range is set between 0 and 10, but you can use any range you like and the function will generate numbers between it. Be careful tough, the output will always be smaller than (not equal to) the max value.
Get an integer within a range
In some cases you need an whole number instead of a decimal number. In math a whole number that can be both positive or negative is called an integer Most programming languages have an integer data type for this occasion, but JavaScript doesn't. It uses the Number data type, containing floating point values, for every type of number. To go from decimal to whole number you'll need to apply a form of rounding.
The next function uses Math.floor() to turn a decimal floating point number into an integer. It returns numbers between a min- and max value. You can read more about the floor() function here.
This time, the results will include both the min and the max.
function getRandomInt(minInt, maxInt) {
return Math.floor(Math.random() * (maxInt - minInt + 1)) + minInt;
}
getRandomInt(0, 10)
//Possible output
6
2
10
0
Generate a random boolean
From random integers it is only a small step to random boolean values. A boolean in JavaScript can have a value of true or false. If you apply the integer technique to generate a number between 0 and 1, you can easily use the outcome to generate random booleans. This can be helpful if you're just looking for a randomized true/false value.
function getRandomBoolean() {
return getRandomInt(0, 1) > 0;
}
Convert an integer to boolean in JavaScript
There are many ways to convert an integer to a boolean. You could also use the ! or == operators, or the Boolean object. Here's an alternative approach to the previous example using a double bang operator:
function getRandomBoolean() {
return !!getRandomInt(0, 1);
}
getRandomBoolean()
//Possible output
true
true
false
true
Creative ways to use random values
When you create a game or animation you can't really go without random values. You can apply the techniques covered in this tutorial to spicy up your work and make it feel less scripted. Here are some fun and practical ways in which random values can be applied:
- Use randomness in animations to make small differences in size, color or motion. This will make the animation less static.
- Play sounds with a random pitch, so no sound sounds the same, but you can still use the same source files.
- Generate particle effects by creating particles with random locations, speed and decay time.
- Randomize boss behaviour to make boss battles less artificial.
Can you seed the random number generator?
In some programming languages it is possible to manually set the seed for the random numbers. You can tell the random() function where to start getting its random numbers, so to say. So, when you have a piece of code that generates ten random numbers, you can start back at the top by setting the same seed and get the exact same ten 'random' numbers again when you re-run the script.
In JavaScript however, setting your own seeds is not natively supported. You could use (or build) an external random number generator to do the job. But always be sure to check if the generator is truly random and the numbers are uniformly distributed.
Conclusion
As you can see it's actually quite easy to generate random values with the Math object. With some effort you can transform them into useful numbers or even booleans. Always be sure to check if your functions return values that are uniformly distributed.
Random numbers are essential for animations and games and make them feel less scripted. With the examples given in this tutorial you can try to find new ways to apply random numbers. If you have any questions feel free to ask them in the comment section below.
Leave a comment