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

SeHyun Choi
SeHyun Choi
3,441 Points

Looping word game challenge

I went back all the things I learned and tried to eliminate lot of repetitive code by using for loop.

But it doesn't work as I want it to. Any advice?

Code

var noun;
var adjective;
var verb;
var question = 3;
var questionsLeft="[There are " + question + " questions left]";


for(i=1; i<=2; i+= 1) {

    noun = prompt("type noun" + questionsLeft);
    question = question + 1;
    questionsLeft="[There are " + question + " questions left]";

    adjective = prompt("type adjective" + questionsLeft);
    question = question + 1;
    questionsLeft="[There are " + question + " questions left]";

    verb = prompt("type verb" + questionsLeft);


}
var message = "There once was a " + noun + ".";
message = message + " The " + noun + " was very " + adjective + " and liked to " + verb;

document.write(message);

1 Answer

Steven Parker
Steven Parker
229,695 Points

Good idea, you can certainly make this project a lot more compact that way.

If I understand what you were shooting for, you will need to replace the individual variables for "noun" and "adjective" with an array to store the responses. And you still have some repetition inside the loop that you can eliminate by having another array with the names of the word types being asked.

The bulk of the program can then be potentially reduced to 1 line:

var word = ["a noun", "an adjective", "a verb"]
           .map((term,i) => prompt(`Enter ${term} [there are ${3-i} questions left]`));

The output would just need to be adapted to use the "word" array, with the proper index for each.

I realize that I may have used a few tricks you haven't gotten to yet, but you can still have a much smaller program by applying these principles with the syntax you know already.