How to get random element from array with JavaScript

Imagine you have an array of numbers.

Goal is to get a random element of an array. There are several solutions posted on But most of them are just too complicated, so I created my solution.

I have extend Array to add function random. What is does it uses random number and length of array to create a random index. Let’s use it in action.

That’s it. Happy coding.


Actually it’s very bad practice to extend prototype. Reasons are problems with browser compatibility. It’s better to create a function and use it. Or you can always use libs like underscore and it’s method sample.

Hi, I'm Erol
Senior Fullstack Developer

I'm available for hire. So if you need help, send me an email.