Access a Random Element in an Array
In this example, we use the
Math.random()
function to access a random element in an array of New England state names.
var states = ['Connecticut', 'Maine', 'Massachusetts', 'New Hampshire', 'Rhode Island', 'Vermont'];
The elements in an array can be accessed by index. The first element in an
array is at index 0 and the second element is at index 1. Since there are six
elements in this array, we could generate a random index using
Math.floor(6 * Math.random())
,
which generates a random integer between 0 and 5. The last index of an array
with six elements is index 5 because the first index is 0.
However, it is generally not a good idea to assume that an array will always have
six elements. Instead of hardcoding the number 6 in our random index generator, we
can use the array's
length
property instead. Because the
states
array currently has six elements,
states.length == 6
.
But if we add or remove elements later, the
length
property is automatically updated to reflect the new number. This makes using the array's
length
property to generate a random index much more robust than hardcoding a fixed number.
var i = Math.floor(states.length * Math.random()); // Generate a random index
var randomStateName = states[i]; // Use the random index to access a random element in the array
Try adding or removing names from the
states
array. The expression for generating a random index always selects an index in the appropriate range.
To learn more about variables and arrays, visit the
Variables
and
Arrays
lessons.
Quick Reference:
Variables
round() / floor() / ceil()