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

JavaScript

Random Quote generator

i just finished the quote generator project and then i started to go thru and look at other peoples solutions to see if there was anywhere i could improve in the future after a while i ran across this code and i cannot seem to figure out how this persons getRandomQuote function works can someone please explain

var quotes = [ { quote: "The only thing to fear is fear itself.", source: "Franklin Delano Roosevelt", citation: "First Inaugural Address", year: 1932, }, { quote: "That's one small step for man, one giant leap for mankind.", source: "Neil Armstrong", citation: "The moon", year: 1969, }, { quote: "It always seems impossible until it is done.", source: "Nelson Mandela", citation: "", year: "1918 - 2013", }, { quote: "Not everything that can be counted counts, and not everything that counts can be counted.", source: "Albert Einstein", citation: "", year: "1879 - 1955", }, { quote: "What we think, we become", source: "Buddha", citation: "", year: "", }, { quote: "Dream big and dare to fail", source: "Norman Vaughan", citation: "", year: "1905 - 2005", }, ];

function getRandomQuote(array) { var quoteIndex = Math.floor( Math.random() * (quotes.length)); for (var i = 0; i < array.length; i++) { var randomQuote = array[quoteIndex]; } return randomQuote; }

function printQuote() { var message = "";
var result = getRandomQuote(quotes); message = "<p class='quote'>" + result.quote + "</p>"; message += "<p class='source'>" + result.source; message += "<span class='citation'>" + result.citation + "</span>"; message += "<span class='year'>" + result.year + "</span>" message += "</p>";

document.getElementById('quote-box').innerHTML = message; }

printQuote();

document.getElementById('loadQuote').addEventListener("click", printQuote, false);

1 Answer

Steven Parker
Steven Parker
228,978 Points

Not every post is an example of good or working code. This particular example has a loop in the "getRandomQuote" function that is entirely unnecessary.

Otherwise, the code seems pretty typical, was there something else about it that seems confusing?

Could you send plain an example of code that performs the same function but doesn’t use a loop

Steven Parker
Steven Parker
228,978 Points
function getRandomQuote(array) {
  var quoteIndex = Math.floor(Math.random() * array.length);
  return array[quoteIndex];
}