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

Trying to concatenate strings and variables in the conditionals but not working

I'm trying to concatenate variables with the string in the initial "if" statement but its not working. var correctAnswers = 0;

This is a sample of the code below.

var question1 = prompt("What is the capital of Cameroon?");

if (question1.toUpperCase() === "YAOUNDE"){ alert("You are correct!. Four more questions coming up " + correctAnswers += 1 ) ; } else{ alert("You are wrong!!!, You have four more tries though"); }

Please put the code in code.

var question1 = prompt("What is the capital of Cameroon?");

if (question1.toUpperCase() === "YAOUNDE")
{ alert("You are correct!. Four more questions coming up " + correctAnswers += 1 ) ; 
} else{ 
alert("You are wrong!!!, You have four more tries though");
}

1 Answer

Hi there,

Going to first stick your code into code formatting for reference:

var correctAnswers = 0;
var question1 = prompt("What is the capital of Cameroon?");

if (question1.toUpperCase() === "YAOUNDE") { 
   alert("You are correct!. Four more questions coming up " + correctAnswers += 1 ) ; 
} else { 
   alert("You are wrong!!!, You have four more tries though"); 
}

The key line here is this one:

alert("You are correct! Four more questions coming up " + correctAnswers += 1 ) ; 

While I believe you can do this, you need to put the calculation in parentheses for it to work. Otherwise, it will assume that the + sign is another attempt to concatenate and it will cause an error.

If you do it like this, for example:

alert("You are correct! Four more questions coming up " + (correctAnswers += 1 )) ; 

it will print "You are correct! Four more questions coming up 1" if they get it right. If that's the intention, I would suggest labeling it in some way, like "Correct so far: " or something like that. If you don't want to print the correct answers each time they get one right, you don't actually need to concatenate, and should just increment correctAnswers on a separate line, like this:

alert("You are correct! Four more questions coming up ") ; 
correctAnswers += 1;

That's up to you though - it depends on what you were originally intending, so I just gave examples for both. Hope this helps!