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 JavaScript Basics (Retired) Working With Numbers The Mad Libs Challenge Revisited

Regio Abundan
Regio Abundan
5,082 Points

Is there a more concise method of doing this?

Do we really need to type a bunch of code for this? What if we have 100 questions to ask?

2 Answers

Lin Lu
Lin Lu
29,171 Points

You could use an array to store the questions, then loop through all of them and store the answers to these questions in another array.

var questions = ['Please type an adjective', 'Please type a verb', 'Please type a noun'];
var questionsLeft;
var answers = [];
while(questions.length > 0) {
  questionsLeft = ' [' + questions.length + ' questions left]';
  answers.push(prompt(questions.shift() + questionsLeft));
}

alert('All done. Ready for the message?');

var sentence = "<h2>There once was a " + answers.shift();
sentence += ' programmer who wanted to use JavaScript to ' + answers.shift();
sentence += ' the ' + answers.shift() + '.</h2>';
document.write(sentence);

The array methods used here are shift() and push(). The shift() method removes the first element from an array and returns that element. The push() method adds one or more elements to the end of an array.

Beautifully implemented solution! There's a lot to learn from your approach to this challenge. Thanks for sharing! Turned into a note for future reference. :)

Lin Lu
Lin Lu
29,171 Points

Thanks Fidel, glad it helped! :D

Regio Abundan
Regio Abundan
5,082 Points

Haven't got to arrays and loops but I'll look into it once I reach the lessons. Thanks a bunch!

Lin Lu
Lin Lu
29,171 Points

You're welcome! :-)