how to get a random element of an array javascript 1

how to get a random element of an array javascript

var items = ['Yes', 'No', 'Maybe'];
var item = items[Math.floor(Math.random() * items.length)];

Here is what the above code is Doing:
1. We create an array called items.
2. We create a variable called item.
3. We use Math.random() to generate a random number between 0 and 1.
4. We multiply that number by the length of the items array (3).
5. We use Math.floor() to round the number down to the nearest whole number.
6. We use that number to get an item from the items array.

Similar Posts