For example, given this array:
var myArray = [‘January’, ‘February’, ‘March’]; What’s the best way to JavaScript pick random from array so I can get one of these months randomly?
For example, given this array:
var myArray = [‘January’, ‘February’, ‘March’]; What’s the best way to JavaScript pick random from array so I can get one of these months randomly?
I’ve used this in dozens of projects—sometimes the simplest way is also the most reliable. The classic trick to javascript pick random from array is using Math.random()
with Math.floor()
:
const randomValue = myArray[Math.floor(Math.random() * myArray.length)];
console.log(randomValue);
It’s fast, intuitive, and your teammates will get it without scratching their heads.
Totally agree, Dipen. After working on a few shared libraries, I’ve found that wrapping this logic in a utility function helps keep things clean and reusable. Especially when you need to javascript pick random from array in multiple spots.
function pickRandom(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
console.log(pickRandom(myArray));
Just makes your code easier to maintain and you only need to write it once.
Nice! And if you’re working with modern JavaScript environments, here’s a slight enhancement. I’ve been using .at()
recently—it’s cleaner and handles edge cases better in some scenarios. So if you’re already using modern syntax, this is another way to javascript pick random from array:
const randomValue = myArray.at(Math.floor(Math.random() * myArray.length));
console.log(randomValue);
It doesn’t change the logic much, but it’s a nice little upgrade if your environment supports it.