Unexpected token {


I have no idea what is wrong with my code. Every time I run it, I get an error message saying "Syntax Error: Unexpected Token". Can anyone please help me?

var slaying = true;
var yourHit = Math.floor(Math.random() ) * 2;
var damageThisRound = Math.floor(Math.random() ) * 5 + 1;
var totalDamage = 0;
 while(slaying) {
    if(yourHit = 1) {
        console.log("You hit the dragon!");
    else(yourHit = 0) {
        console.log("The dragon incinerated you!");
    slaying = false;

Syntax error: Unexpected token { . What's wrong with my code? It looks the same with the code in the Hint but I'm still getting that error

Remove the brackets around the else statements console.log


The brackets aren't the problem, wrote a longer post about them over there:

Yes in this case omitting them gets rid of the error message but it doesn't get rid of the problem!
And the problem(s) are the conditions and I'm using the (s) here because both of them are problematic.

yourHit = 1

is a problem because it uses the = operator which means, unlike in math, assign the value on the right of it to the variable on the left of it. Which in this case has the side effect that the value of name=VALUE is VALUE, here VALUE is 1 so this case is always chosen no matter what youHit originally was. For comparing values you're better of using the == (compares values) or === (compares values + types) operators.

And about the second condition: Well else doesn't have a condition. It means "if the condition is not true do something else instead", there is no need for further specification and giving some will only lead to confusion and errors. If you need another condition go with else if and if not do not use a condition here.

The problem is as explained in the link that conditions actually work fine without {} but you need to keep in mind that they only expect 1 statement to follow. So what happens in your case is that this:

else(yourHit = 0) {

are actually 2 statements: (yourHit = 0) is the first and { indicates the beginning of the second. Now if you get rid of the brackets you avoid the problem of having 2 statements on one line without separator but you still have the problem that your else conditions this rather pointless statement (yourHit = 0) while the stuff it should actually execute with a condition {console.log("The dragon incinerated you!");} gets shown any time no matter what the value of yourHit is.

I hope this makes some sense otherwise have a look at the link or simply ask and I'll give it another try.


Yes thank you that make perfect sense. I'll pay better attention to that next time when answering people's questions.