Lots of Ways to Use Math.random() in JavaScript

Avatar of Jwahir Sundai
Jwahir Sundai on

Math.random() is an API in JavaScript. It is a function that gives you a random number. The number returned will be between 0 (inclusive, as in, it’s possible for an actual 0 to be returned) and 1 (exclusive, as in, it’s not possible for an actual 1 to be returned).

Math.random(); // returns a random number lower than 1

This is incredibly useful for gaming, animations, randomized data, generative art, random text generation, and more! It can be used for web development, mobile applications, computer programs, and video games.

Whenever we need randomization in our work, we can use this function! Let’s look at eight different ways we can use it. These examples are all from different authors doing something interesting with this API.

Animation

To spawn an object and animate it, we use Math.random. The neon lines form spontaneous hexagons but randomization is also in its generative sparks. 

Computer-generated music

This program takes the traditional melody of “Auld Lang Syne” and plays random notes from it in piano. A change package is created from the count data and a random number is generated to select a value. The octave is also randomly selected.

Display a random image

Images are stored in an array. A number is generated and multiplied by the number of images in the array via array.length. Then Math.floor rounds the value to a round number and sets the image src in the HTML when the page is loaded or the button is clicked.

Random background color

This is where the magic happens:

const random = (min, max) => {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

The first line of code randomly shuffles the array and the second line returns a random umber between 0 and 10. In the example of a random color background, the range of colors and specifics such as hues, saturations, and shades can be set. 

For another method for generating a random hex color, check out this article by Chris Coyer. 

Generative art

In this morphing fractal curve, Math.random is used twice to set the colors for the gradient and once more for the max radius of the curves. This is a great way to construct an entirely new appearance with every iteration!

Word generator

We replace the header with a randomly selected word from an array using Math.random:

var word = words[Math.floor(Math.random() * words.length)] + "!";

This is a lot like the random image example — the perfect sort of practice for beginners! 

API key generator

Here’s a super real-world practical use case for random numbers! The demo generates 16 random numbers to create a universally unique identifier (UUID) that can be used as a key that provides access to an API.

Text scramble

A few phrases are stored and displayed in sequence, separated by an animation that appears to scramble the letters with random characters between phrases that are selected by Math.random.

Rock Paper Scissors

In this childhood classic game of Rock Paper Scissors, Math.random is used to generate a randomized move for the computer playing as the opponent. It makes a pick from the three available moves.

Strong Password Generator

This password generator uses Math.random to get a password array filled with uppercase and lowercase letters then adds random digits to the generated password. This is another great practical example!

A couple of notes…

It’s possible you have questions after seeing Math.random in these examples. There are a couple I see come up often…

Is Math.random() really random?

Not exactly. Math.random() returns a pseudo-random number. This algorithm is called a pseudo-random number generator (or PRNG). This means its randomization can be reproduced under certain circumstances. 

The randomization is based on the algorithm xorshift128+, which is likely running on your browser.

So, it’s random-ish.

How do you handle repeated values?

There are many methods to achieve unique values without repetition. The Fisher-Yates is one great way to prevent getting the same number twice by shuffling the sequence. Math.random will select a value from the shuffled array of a finite sequence demonstrated by the code snippet below.

function shuffle (array) {
  var i = 0
    , j = 0
    , temp = null

  for (i = array.length - 1; i > 0; i -= 1) {
    j = Math.floor(Math.random() * (i + 1))
    temp = array[i]
    array[i] = array[j]
    array[j] = temp
  }
}

Is Math.random() the same as WebCrypto?

As you’ve seen from this article, Math.random() is awesome! However, if you dealing with sensitive applications and need a more secure method of randomization, I’d recommend WebCrypto. Reasons you may want to use WebCrypto include temporary verification codes, random password generation, randomized lottery numbers, etc. 

If you need randomization for the purposes of cybersecurity, cryptography, or statistics ,  use the function window.crypto.getRandomValues and check out Mozilla’s documentation on the WebCrypto API.