[JavaScript] How to get a random element from an array?


I want to read a random element from the array, how can I do that in Javascript?

1 Answer

3 years ago by

Using Math.floor(Math.random() * array.length), we can generate a random number of length less than Array size and we can use that as index to pick a random element from array. Following code shows how to do that

let numbers = [10,20,30,40,50,60,70,80];
console.log(numbers[Math.floor(Math.random() * numbers.length)])

Try running this code online here: https://onecompiler.com/javascript/3xmzvczky

3 years ago by Meera