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!

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


Review of my printQuote() Function

Hi there,

Please I want a review of my code because when I try to run the code it displays "undefined" on the page. I've realized the problem is with the printQuote function but I can't quite figure it out.

// An array of Objects with the quote and source as properties
var quotes = [
        quote: "In the end, it’s not the years in your life that count. It’s the life in your years",
        source: "Abraham Lincoln",

        quote: "Don’t gain the world and lose your soul, wisdom is better than silver or gold",
        source: "Bob Marley",

        quote: "Lighten up, just enjoy life, smile more, laugh more, and don’t get so worked up about things",
        source: "Kenneth Branagh",

        quote: "Don’t cry because it’s over, smile because it happened",
        source: "Ludwig Jacobowski",

        quote: "Do stuff. Be clenched, curious. Not waiting for inspiration’s shove or society’s kiss on your forehead. Pay attention. It’s all about paying attention. Attention is vitality. It connects you with others. It makes you eager. Stay eager",
        source: "Susan Sontag",


// getRandomQuote function selects and returns a random quote object
function getRandomQuote() {
    var quoteIndex = Math.floor(Math.random() * quotes.length);  // selects a random quote
    return quotes[quoteIndex];  // returns the random quote

//printQuote function
function printQuote(message) {
    var result = getRandomQuote(); // Calls and stores the getRandomQuote in a variable
    var message = "<p class='quote'>" + quotes.quote + "</p>" +"<p class='source'>" + quotes.source + "</p>";
    document.getElementById('quote-box').innerHTML = message;


// event listener to respond to "Show another quote" button clicks
// when user clicks anywhere on the button, the "printQuote" function is called
document.getElementById('loadQuote').addEventListener("click", printQuote, false);

2 Answers

Steven Parker
Steven Parker
227,126 Points

When you call "getRandomQuote", you store the returned object in the variable "result ", but when you build the message, you refer to "quotes" instead. Fix it by changing your references to use "result":

    var message = "<p class='quote'>" + result.quote + "</p>" +
                  "<p class='source'>" + result.source + "</p>";

It worked, how didn't I see that? Thanks very much!!!