Skip to content

How to get a random item from a JavaScript array

var myArray = ['a','b','c'];
var randomItem = myArray[Math.floor(Math.random()*myArray.length)]

Math.random() returns a number between 0 (included) and 1 (not included), which is why this piece of code won’t overshoot by picking a number equal to the array length (reminder: array indexes start at 0, meaning last index is length – 1).

Math.round() is not appropriate as it would result in sometimes hitting a number equal to the array length. Hence the Math.floor().

Posted in JavaScript / TypeScript / Node.js.

0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

Some HTML is OK

or, reply to this post via trackback.

Sorry about the CAPTCHA that requires JS. If you really don't want to enable JS and still want to comment, you can send me your comment via e-mail and I'll post it for you.

Please solve the CAPTCHA below in order to fight spamWordPress CAPTCHA