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

Why is repetition of questionsLeft command necessary?

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 for ' + verb; sentence += ' the ' + noun + '.</h2>'; document.write(sentence);

--

Can someone explain to me why the "questionsLeft" command is needs to be repeated before each question? It just doesn't make sense to me, if all that is changing is the integer value of the question variable.

2 Answers

Francisco Ruiz
Francisco Ruiz
14,213 Points

Hi Nelson - questionsLeft is the variable that holds 3 versions of the String "[X questions left]" where X is the questions Integer variable and is set to 3, 2, or 1, depending on how many times there was been a " - 1" operated on it i.e. questions -= 1. Since questions has a different value after each prompt function call, the questionsLeft string needs to be updated to reflect this change i.e. questionsLeft = ' [' + questions + ' questions left]';

Hope that helps :)

Ross Horak
Ross Horak
20,890 Points

Hi Nelson,

This also confused me a little bit.

I would have thought that 'questionsLeft' value would have updated automatically as the 'questions' variable is updated and forms part of the 'questionsLeft' value. This is obviously not the case, and one needs to update both variables.

I did my own test of this in a JS Console with the following: var a = 1; var b = 2; var c = a + b; var a = 2; console.log(c) //will still return a value of 3, and not 4 as we both initially expected. To solve you would have to restate var c = a + b; after updating the value of a.