0

I am working on a random quote generator, where I first randomly generate a number between 0 and the length of the array 'quotes,' then return that quote.

function getQuote() {
 var quotes = ["I never met a toby that I didn't like ~ Kimya Dawson", "Blood in my beard ~ Aesop Rock", "How many roads must a man walk down? ~ Bob Dylan", "Orange is the new black ~ Jenji Kohan"];

function randomNumber(min, max) {
 var quote = Math.floor(Math.random() * (max - min +1)) + min
 return quotes[quote]; 
}; 
return randomNumber(0, quotes.length);
};
getQuote();

It works most of the time, but every so often it will return 'Undefined.' I did not have this problem when testing with an array of single words like 'hello,' 'green,' etc., it only happens when I add spaces.

3 Answers 3

2
Math.floor(Math.random() * (max - min +1)) + min

can return max which points to a non-existing array element. Array indices go from 0 to length - 1.

It should be

Math.floor(Math.random() * (max - min)) + min
Sign up to request clarification or add additional context in comments.

Comments

1

That +1 in the code that finds a random index is your problem.

There are 4 quotes, so max is 4. 4-0+1 is 5, not 4, so you're going to generate the value 4 every once in a while, and there is nothing at that position in the array. (The quotes are at indexes 0, 1, 2, and 3.)

Comments

0

Arrays starts from 0, so in your case max is 3 (quotes[3]). However length function returns number of elements (4).

return randomNumber(0, quotes.length-1);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.