Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
brandonlind2
7,823 Pointsany idea as to why this random word function isnt working?
The randomWord function keeps returning undefined for some reason
var words=[
'car',
'dog',
'mouse',
'hotel',
'car'];
function randomWord(list){
var random_num= Math.floor(Math.random() * list.length) +1;
var word=list[random_num];
return word
}
randomWord(words)
1 Answer
Travis Flatt
20,149 PointsIt sorta does. The Math bits are throwing you out of range occasionally, so there'll be an undefined here and there.
var words=[
'car',
'dog',
'mouse',
'hotel',
'car'];
function randomWord(list){
var word=list[Math.floor(Math.random()*list.length)];
console.log(word);
}
randomWord(words);
That +1 in the original is what you'd want to use if you were looking for a non-zero random number, but you're using it for an array index, which is zero-based (So, you'll occasionally get that undefined when the result is higher than the available indices go).