Getting a Random Index Number
Array indexes start at 0 and count up until the final element. Therefore we need to pick a random number between 0 and the length of the array minus 1. We can do this multiplying the output of
Math.random() by the length of the array and rounding that down to a whole number using
var fruits = ['apple', 'strawberry', 'orange', 'apricot']; var rand_index = Math.floor(Math.random() * fruits.length); console.log(rand_index);
Learn more about how the Math.random() function works.
Accessing the value
To access the randomly picked index we can pass the number inside
 (square brackets) on the array variable.
var rand_val = fruits[rand_index]; console.log(rand_val);
array index random number