Hello CodeNewbie! I'm teaching myself JavaScript right now and am having a hard time with selecting a random item from a JavaScript array. Can anyone help illuminate the issue for me?
Cheers!
Hello CodeNewbie! I'm teaching myself JavaScript right now and am having a hard time with selecting a random item from a JavaScript array. Can anyone help illuminate the issue for me?
Cheers!
For further actions, you may consider blocking this person and/or reporting abuse
Hiredeveloper -
Sarah Dye -
swiftproxy -
Hiredeveloper -
Top comments (1)
Hello Harry.
So array indices go from 0 to array.length - 1. When selecting a random item, we want to get a random integer (whole number) within that range.
Knowing this, we can define a function
getRandomElement
that takes in an array and returns a random element from the given array. I defined it as a function assuming you would use this more than once. It's good practice to do this to avoid repeating code (DRY: Don't Repeat Yourself).Resources:
Math.floor
Math.random