Getting a random value from a JavaScript array

Consider:

var myArray = ['January', 'February', 'March'];    

How can I select a random value from this array using JavaScript?

27 s
27

It’s a simple one-liner:

const randomElement = array[Math.floor(Math.random() * array.length)];

For example:

const months = ["January", "February", "March", "April", "May", "June", "July"];

const random = Math.floor(Math.random() * months.length);
console.log(random, months[random]);

Leave a Comment