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

Caleb Cox
seal-mask
.a{fill-rule:evenodd;}techdegree
Caleb Cox
Full Stack JavaScript Techdegree Student 7,765 Points

If there is no property of year, printQuote() prints out "undefined" for the year span. How do I make this stop??

Here is my code:

//selects random quote var getRandomQuote = function() { //holds random number from 0 to quote.length var randomNum = Math.floor(Math.random() * quotes.length); //iterates through quotes array to select an object for(randomNum; randomNum < quotes.length; randomNum++){ //returns selected object return quotes[randomNum]; } }

//prints quote var printQuote = function() { //calls returned quotes object var getQuote = getRandomQuote(); //builds html text using the selected object's keys var html = "<p class='quote'>" + getQuote.quote + "</p>"; html +="<p class='source'>" + getQuote.source; html +="<span class='citation'>" + getQuote.citation + "</span>"; html +="<span class='year'>" + getQuote.year + "</span>"; html +="</p>"; //puts the constructed html into the 'quote-box' div document.getElementById('quote-box').innerHTML = html;

----------------THIS IS HOW IM TRYING TO SOLVE IT--------------------

if(getQuote.hasOwnPropery('year') === null){ html-="<span class='year'>" + getQuote.year + "</span>"; }

---------------------------------------------------------------------------------- }

//click button to load random quote document.getElementById('loadQuote').addEventListener("click", printQuote, false);

1 Answer

Damien Watson
Damien Watson
27,419 Points

Hi Caleb,

You can check whether getQuote.year is undefined and then choose what to do next by using:

if (getQuote.year === undefined) {
  alert("it's undefined!");
}

ps. You can format your code using the Markdown Cheatsheet, this will help people understand your question and more likely to get a response other than 'please format your code' ;)