Mailchimp: Grow sales with Customer Journey Smarts
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).
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.
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.
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.
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.
This is where the magic happens:
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.
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!
We replace the header with a randomly selected word from an array using Math.random
:
This is a lot like the random image example — the perfect sort of practice for beginners!
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.
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.
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.
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!
It’s possible you have questions after seeing Math.random in these examples. There are a couple I see come up often…
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.
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.
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.
Frontend Masters is the best place on the web to really learn JavaScript. They have a complete learning course from the biggest and best teachers in JavaScript to help you make the most out of the web’s biggest language.
Frontend Masters is the best place on the web to really learn JavaScript. They have a complete learning course from the biggest and best teachers in JavaScript to help you make the most out of the web’s biggest language.
source