JavaScript Random Generator Made Simple
While brushing up on my JavaScript and working on an exercise to randomly change the background color of a .html file at the click of a button, I was confused by a single line of code that involved understanding use of an array, the array.length property, Math.floor()function and the Math.random()function.
This project is from the first sixteen minutes of Basic JavaScript Projects series by Coding Addict. I’ll refrain from reviewing the project in its entirety as that’s not the goal of this article. In this post, I break down the line of code that stomped me initially, in minute detail for two reasons:
1.) Writing out a problem and then steps to solve it assist in my understanding of a concept at its core, thus allowing me to convert data from short to long-term memory
2.) To hopefully help others who’ve stumbled upon the same logic roadblock
Here’s the line of code in plain English reads:
“Generate a random number. After the random number is generated, multiply it by the length of the array. Then, round the product of the randomly generated number and length of the array to its floor.”
Math.floor(Math.random() * arrayOfColors.length);
So let’s start this process from the beginning, from start to finish, and break this code down.
Step 1: Create an array. Name the array arrayOfColors. The array should have four elements total, with a color listed as each element.
const arrayOfColors = [‘yellow’, ‘red’, ‘green’, ‘blue’];
Step 2: Understand the definition of an array
An array is a data structure consisting of a collection of elements, each identified by at least one array index or key Wikipedia. Important to note, arrays start at an index of 0. The color yellow is represented by index 0, not 1, red an index of 1, green 2 and blue 3.
Step 3: Understand the JavaScript function used to generate a random number
The Math.random() function returns a floating-point, pseudo-random number in the range 0–1 (inclusive of 0, but not 1) with approximately uniform distribution over that range — which you can then scale to your desired range.
Step 4: Determine the length of the array using the array.length property
The length property returns the number of elements in that array.
If you typed the following in the console, using the length property, the return value would be 4: console.log(arrayOfColor.length);
Step 5: Scale the random number generated to your desired range using the arrary.length property
Multiply the random number generated by the length of the array. This will provide a range of selection that will never be more than the length of the array.
For example, if the random number generated by the Math.random() function is 0.24, we can’t use this to select an element of an array by its index number. However, since we know the length of the array is 4, we can multiply the random number by the array length, which offers a range of numbers to choose from between 0 and 4. This is how we scale the random number generated to the desired range.
0.24 * 4 = 1.04
Of course, there isn’t an index of 1.04, so we need the nearest integer down. To accomplish this, we use the Math.floor()function. The floor of 1.04 is 1. Now we have the number 1, which reflects index 1 of the array, which holds the element with a string ‘red.’ This is how you can randomly target an element in an array.
If you need a refresher on floor and ceiling function, please view the diagram below.
Now, let’s revisit the line of code again. Remember it reads:
“Generate a random number. After the random number is generated, multiply it by the length of the array. Then, round the product of the randomly generated number and the number of length of the array to its floor.”
Math.floor(Math.random() * arrayOfColors.length);
If you care to review the complete version, here’s the CodePen and the Github repository.
Thanks for reading.
Until next time,
Astra Rai
Other articles I’ve written about relearning JavaScript: