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

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
229,657 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
229,657 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
229,657 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