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) Making Decisions with Conditional Statements The Conditional Challenge Solution

Carlos Federico Puebla Larregle
Carlos Federico Puebla Larregle
21,073 Points

Could we use only one "answer" variable for this challenge?

I have it pretty much the same as the professor has it but I use it only one "answer" variable and used it for all the 5 prompts. I don't know is that is or it isn't a good practice. Here is my code:

// quiz begins, no answer counter as correct var counter = 0;

//ask questions var answer = prompt("What is the best programming language?");

if (answer.toLowerCase() === 'javascript') { counter += 1; }

answer = prompt("You should be putting a semicolon after a if condition?");

if (answer.toLowerCase() === 'no' || answer.toLowerCase() === 'n') { counter += 1; }

answer = prompt("What function do we use in javascript to lover case all letters?");

if (answer.toLowerCase() === 'tolowercase()' || answer.toLowerCase() === 'tolowercase') { counter += 1; }

answer = prompt("What function do we use in javascript to upper case all letters?");

if (answer.toLowerCase() === 'touppercase()' || answer.toLowerCase() === 'touppercase') { counter += 1; }

answer = prompt("What math function do we use in javascript to generate random numbers?");

if (answer.toLowerCase() === 'math.random()' || answer.toLowerCase() === 'random()' || answer.toLowerCase() === 'random') { counter += 1; }

if (counter === 5) { document.write("<p>You just win the GOLDEN CROWN!</p>"); } else if(counter === 4 || counter === 3) { document.write("<p>You just win the SILVER CROWN!</p>"); } else if (counter === 2 || counter === 1) { document.write("<p>You just win the BRONCE CROWN!</p>"); } else { document.write("<p>Sorry, you didn't win any crown at all.</p>"); }

1 Answer

Steven Parker
Steven Parker
229,732 Points

:information_source: Re-using the variable makes sense in this case, because after the conditional statement following the prompt, it would otherwise be unused for the remainder of the scope. Additionally, the variable is always being used the same way, so its name remains appropriate to its use.

:recycle: This is conservative of the memory resource and is good practice.