Getting a random value from a JavaScript array Getting a random value from a JavaScript array javascript javascript

Getting a random value from a JavaScript array


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]);