Home 13: Random numbers
Content
Cancel

13: Random numbers

There are multiple ways to create random numbers in JavaScript. Let’s have a look at the standard method in JavaScript first.

Creating random numbers in JavaScript

The math package in JavaScript has a command to create a random number between 0 and 1.

1
2
const randomNumber = Math.random();
console.log(randomNumber);

It will create a random number between 0 (including) and 1 (excluding).

When you run this code you will see a random decimal number appear in your console. If we want to use this method to generate a whole number up to a specific boundary, we need to add some more code.

Imagine we want to have a random whole number between 0 and 100, not including 100. We would have to do 3 steps:

  1. Generate a random number between 0 and 1
  2. Multiply this number with 100, our upper boundary
  3. Round the number to the nearest integer
1
2
3
4
let randomNumber = Math.random();
randomNumber = randomNumber * 100;
randomNumber = Math.floor(randomNumber);
console.log(randomNumber);

You can also write the same code in a single line:

1
2
const randomNumber = Math.floor(Math.random() * 100);
console.log(randomNumber);

It is still doing the same thing, but in a more compact way.

We would use Math.floor here, to make sure that we have an equal and fair distribution.

Using the p5.js random function

If you don’t want to calculate on your own you can use a method that is provided by p5.js called random.

1
random([min], [max]);

You can enter the lower bound (inclusive) as a first value and the upper bound (exclusive) as second parameter. If only one value is given, it uses 0 as lower bound (inclusive).

The above example with the random command would look like that:

1
2
const randomNumber = random(100);
console.log(randomNumber);

You notice that the numbers are automatically rounded for you. You can read more about the random command here.

This post is licensed under CC BY 4.0 by the author.