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

It doesn't work

var question = 4; var result = 0; var askQuestion = ' [ ' + question + ' questions left ] '; var q1 = prompt('Is the water blue or red?' + askQuestion); if(q1 === 'blue') result += 1; question = 3; var q2 = prompt('Is the blood blue or red?' + askQuestion); if(q2 === 'red') result += 1; question = 2; var q3 = prompt('What is the capital of Thailand?' + askQuestion); if(q3 === 'Bangkok') result += 1; question = 1; var q4 = prompt('What is the capital of England?' + askQuestion); if(q4 === 'London') result += 1; question = 0; var q5 = prompt('What is the captal of china?' + askQuestion); if(q5 === 'Beijing') result += 1;

alert('There are ' + result +' correct answers');

if(result === 5) document.write('Gold Crown'); else if(result === 4 || result === 3) document.write('Silver Crown'); else if(result === 2 || result === 1) document.write('Bronze Crown'); else document.write('No Crown');

I want to know why the 'askQuestion' has the problem; The first question: Is the water blue or red? [ 4 questions left] The 2nd question: Is the blood blue or red? [ 4 questions left] The 3rd question: What is the capital of Thailand? [ 4 questions left]

Steven Parker
Steven Parker
221,328 Points

When posting code, always use the instructions for code formatting in the Markdown Cheatsheet pop-up below the "Add an Answer" area. :arrow_heading_down: Or watch this video on code formatting.

1 Answer

Steven Parker
Steven Parker
221,328 Points

The string askQuestion never changes.

You create that string before the first question is asked, and then included it with every question. But it's just a plain string that never changes.

Perhaps you intended to create a function instead of a string?

var askQuestion = () => ' [ ' + question + ' questions left ]';   // function instead of string
var q1 = prompt("Is the water blue or red?" + askQuestion());     // function called using ()'s

OK, But I want to create a string. Why is it just a plain string that never changes?

Steven Parker
Steven Parker
221,328 Points

You did create a string, and assigned it to a variable. Any variable that is only assigned once never changes. But if you make a function to create the string, then everytime you call that function it makes the string fresh.

Ok, I got it. Thank you