How to get a random element from an array in JavaScript?
Hello everyone! I'm new to JavaScript and ran into a problem. I have an array with user names:
```javascript
const users = ['Anna', 'Boris', 'Victor', 'Galina', 'Dmitry'];
```
I need to write a function that will return a random name from this array. I know that JavaScript has `Math.random()`, but I don't understand how to apply it to an array.
I tried doing this:
```javascript
function getRandomUser() {
const randomIndex = Math.random();
return users[randomIndex];
}
```
But it doesn't work — it returns `undefined`. I understand that `Math.random()` returns a number from 0 to 1, not an array index. How do I correctly convert a random number into an index?
I'm also interested in how to make the function work with any array, not just
No answers yet.
Log in to leave an answer