Borislav Hadzhiev
Thu Oct 28 2021·2 min read
Photo by Anubhav Saxena
To get a random element from an array use the Math.floor()
and Math.random
functions to get a random array index, e.g.
arr[Math.floor(Math.random() * arr.length)]
. The expression returns a random
array index, which you can access to get a random array element.
const arr = ['one', 'two', 'three', 'four', 'five']; const random = arr[Math.floor(Math.random() * arr.length)]; console.log(random); // 👉️ three
The expression in the square brackets []
evaluates to a random index in the
array.
The Math.floor function, rounds a number down if the number has a decimal, otherwise it returns the number as is.
console.log(Math.floor(4.99)); // 👉️ 4 console.log(Math.floor(4.01)); // 👉️ 4 console.log(Math.floor(4)); // 👉️ 4
The
Math.random
function returns a random number in the range 0
to less than 1
. The function
could return 0
, but it could never return 1
.
console.log(Math.random()); // 👉️ 0.5434554... console.log(Math.random()); // 👉️ 0.3348588... console.log(Math.random()); // 👉️ 0.8547547... // 👇️ Multiplied by array.length const arr = ['one', 'two', 'three', 'four', 'five']; console.log(Math.random() * arr.length); // 👉️ 1.335... console.log(Math.random() * arr.length); // 👉️ 2.643... console.log(Math.random() * arr.length); // 👉️ 0.393... console.log(Math.random() * arr.length); // 👉️ 4.247...
The max
value we could get is, if Math.random()
returns 0.9999...
and we
multiply it by the array's length (5). We would get back a value of 4.995
.
console.log(0.999 * 5); // 👉️ 4.995
However, because indexes are zero-based in JavaScript and the last element in an
array has an index of array.length - 1
, we use the Math.floor()
function to
round the number down to the next integer, which is 4
(the last index in the
array).
Conversely, the min
value we could get is if Math.random()
returns 0
, we
would then multiply that by the array's length and get 0
back.
console.log(0 * 5); // 👉️ 0
Calling the Math.floor
function on 0
would return the number as is and we
would access the first element in the array.
The expression returns an index from 0
up to (but not including)
array.length
. Using this approach, we could never access an index out of
bounds.
Here's the complete example.
const arr = ['one', 'two', 'three', 'four', 'five']; const random = arr[Math.floor(Math.random() * arr.length)]; console.log(random); // 👉️ five