The first item in the colors sequence is never found for the fuction pickRandom but I don't know why. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

The first item in the colors sequence is never found for the fuction pickRandom but I don't know why.

if anyone knows please explain and fix the code for me to know what is the right way to do it. var colors = [ "red", "green", "blue", "yellow", "purple", "coral", "gold", "white", "black", "brown", "pink" ]; function pickRandom(aList){ return aList[Math.ceil(Math.random() * 10)] }; console.log(colors[Math.ceil(Math.random() * 10)]); document.write(pickRandom(colors)) The code: https://code.sololearn.com/WNHrflhXY2Sy/?ref=app

5th Apr 2020, 10:38 PM
Cafezinho de Dionísio ☕
Cafezinho de Dionísio ☕ - avatar
3 Answers
+ 2
Math.ceil rounds up to the nearest whole number(closest to +∞). Math.ceil(Math.random()*10) won't(almost impossible) return 0. To get a random array element: arr[ Math.floor(Math.random()*arr.length)] is commonly used.
5th Apr 2020, 10:47 PM
Kevin ★
+ 3
You ceil, so round up. Giving you numbers between 1 and 10. 0 is never reached. Instead use... Math.floor(Math.random()*colors.length)
5th Apr 2020, 10:51 PM
HonFu
HonFu - avatar
+ 3
Thank you guys, I can get it now
5th Apr 2020, 10:55 PM
Cafezinho de Dionísio ☕
Cafezinho de Dionísio ☕ - avatar