Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
216,136 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.