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

The Mad Libs Challenge Revisited

On "The mad libs challenge revisited" the author Dave McFarland restates " var questionsLeft" without making an changes to the code multiple times. He does this on line 5, and 8.... which looks like: questionsLeft = ' [' + questions + ' questions left]';

Since he is not making any alterations to the variable, what is the reasoning behind restating the variable multiple times?

var questions = 3;

var questionsLeft = ' [' + questions + ' questions left]';

var adjective = prompt('Please type an adjective' + questionsLeft);

questions -=1;

questionsLeft = ' [' + questions + ' questions left]';

var verb = prompt('Please type a verb' + questionsLeft);

questions -=1;

questionsLeft = ' [' + questions + ' questions left]';

var noun = prompt('Please type a noun' + questionsLeft);

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

var sentence = "<h2>There once was a " + adjective;

sentence += ' programmer who wanted to use JavaScript to ' + verb;

sentence += ' the ' + noun + '.</h2>';


1 Answer

Hi Jonathan!

Good question. The questionsLeft = ' [' + questions + ' questions left]'; line needs to be repeated each time because the questions variable on the line before has been subtracted by one. Note how the questions variable is also included inside the questionsLeft variable. In other words, the questions variable has changed since it was first defined at the very beginning of the code, on line 1.

By including the entire line again, the questionsLeft variable is being updated with the new value of questions (which is being subtracted by 1). If questionsLeft was not updated every time the questions variable was subtracted by 1, it would use the value of the questionsLeft variable shown on line 2 of the code. In this case, questions would be equal to 3 and never change.

Hope that helps!