Profile image of anonymous
Submitted by anonymous
about 11 years

if / else errors - learn how to fix these

If you have a question that isn’t answered here, please use the green “Ask a question” button. Copy/paste all of your code in with your question, include the exercise number you are working on and the exact error message you are seeing.


Typically the following error messages are caused by faulty if/else syntax


  • “syntax error”
  • “missing operand; found else”
  • “Unexpected token else”
  • “expected an identifier and instead saw “else”

First off, a quick review of what if statements look like.

A typical if () statement looks like this. Depending on what you are checking for, the else if and else blocks may not be needed. Note how the { }, ( ) and ; are used.

if (this condition is true) {
    do something;
} else if {
    do this other thing;
} else if {
    do this awesome thing;
} else {
    do something different;
}

Do a quick check to see if you haven’t misspelled or mis-capitalized if or else.

Using any of these is going to earn you an error: IF, If, ELSE, Else

All good with your spelling and capitalization? Okay, on to the next check.


Is there an indicator complaining about your else?

In JavaScript semicolons mark the end of statements.

When you put a semicolon at the end of a condition, like this: if (choice1 === choice2); you are telling the interpreter to consider that as the end of your if statement. Any code following that will be processed without regard for the outcome of that if condition.

If you are getting an error about the else it is because you’ve told the interpreter that the ; was the end of your if statement so when it finds the else a few lines later it starts complaining.

A few examples of where not to put a semicolon:

if (age < 18);
if ( 9 > 10 );
if ("Yogi Bear".length < 3);
if ("Jon".length * 2 / (2+1) === 4 );
if (userAnswer === "yes");
if (feedback > 8);
if (income >= 100);

I think you can see what I’m getting at.


Checked for all those and still haven’t found the bug yet?

Have a look and make sure you don’t have any semicolons on your else or your else if ( ), doing that will also end your if statement sooner than you had planned.

These are both going to give you errors:

} else if (computerChoice < 2/3); {
else;

Curious about other situations where semicolons should be used/not used?

Answer 52537b7eabf821afaa003829

34 votes

Permalink

else is not allowed to have a condition


@AlbionsRefuge - Great post!!

I’ve also noticed a few people trying to do things like…

if ( a < b) {
    do something here;
}
else if (a > b) {
    do this other thing;
}
else (a == b) {
    do something different;
}

and then they post a question asking what is wrong with their code.

It seems that they aren’t grasping a few concepts about the flow of logic in if / else if / else statements.

So I thought this would be a great place to point out a few things that those struggling with if / else if / else might find helpful.

For one thing, unlike if and else if, an else statement is not used to do condition checking. The purpose of else is to execute alternative code in the situation where the if, and else if conditions return false.

In the particular code example above, if the program execution has reached the else statement it means that:

a < b returned false and a > b also returned false.

If the value of a is: not greater than the value of b and not less than the value of b, then it logically follows that the value of a must be equal to the value of b! because there is no other option for what the value of a could be.

There is no need to even bother trying to test for ( a == b ). You simply have the else statement do something.

The correct code would be:

if ( a < b) {
    do something here;
}
else if (a > b) {
    do this other thing;
}
else {
    do something different;
}

I think those of us who are seasoned programmers (or people like me who have just had some exposure to programming concepts and have coded up a few personal projects) tend to take these things for granted.

Pointing them out might seem very elementary to experienced programmers. However, beginners who have never dealt with these concepts can and do struggle with these kinds of ideas and I felt a good explanation might be in order.

I hope this is a helpful comment!

Profile image of anonymous
Submitted by anonymous
about 11 years

25 comments

Profile image of anonymous
Submitted by anonymous
about 11 years

Thanks mrman, I’m sure some of the learners will find this helpful. (I changed the formatting your code blocks, just a bit - too much of that red lettering makes my eyes go funny).

Profile image of anonymous
Submitted by anonymous
about 11 years

No problem, looks good! Thanks!

Profile image of anonymous
Submitted by anonymous
almost 11 years

Thank you! That helped

Profile image of anonymous
Submitted by anonymous
over 10 years

Great post! I Will refer to it often!

Profile image of anonymous
Submitted by anonymous
over 10 years

big help!

Profile image of anonymous
Submitted by anonymous
over 10 years

you rock!!

Profile image of anonymous
Submitted by anonymous
over 10 years

Please with the solution/explanation given to this if and else statement, has anyone used it and gotten it. Because I’ve followed the instruction and still not getting it. Maybe anyone skype with me on this ID- dayor69 for more clarification. Thanks.

Profile image of anonymous
Submitted by anonymous
over 10 years

Thank you! You helped me figure out what I was doing wrong!

Profile image of anonymous
Submitted by anonymous
over 10 years

Yes! Thank you!!

Profile image of anonymous
Submitted by anonymous
over 10 years

These small errors really do make a difference, damn. Thanks you guys for the wonderful explanations!

Profile image of anonymous
Submitted by anonymous
over 10 years

This did it! Thank you for helping me spot my error!

Profile image of anonymous
Submitted by anonymous
over 10 years

Thank You for help

Profile image of anonymous
Submitted by anonymous
over 10 years

You saved my day! Thank you! My error was that I used a statement on Else. Great explaining!

Profile image of anonymous
Submitted by anonymous
over 10 years

it says unexpected identifier for me and i dont know what that means?

Profile image of anonymous
Submitted by anonymous
over 10 years

You probably ended a conditional statement too early by a semicolon or in an other way have a look at the post below this one.

Profile image of anonymous
Submitted by anonymous
over 10 years

Yes thank you. And like you said for those with experience some things are clear to see but to the beginners it can be a nightmare but once you get it, its great.

Profile image of anonymous
Submitted by anonymous
about 10 years

Thanks Mark! People like you make this enjoyable for novices like me. continue being brilliant.

Profile image of anonymous
Submitted by anonymous
over 9 years

Beautiful explanation and yes, very helpful! Thanks Mark. I was initially wondering what was wrong with the code you posted, then it made sense after reading what you wrote.

Profile image of anonymous
Submitted by anonymous
over 9 years

Very helpful, and just had a minor victory thanks to this comment - cheers!

Profile image of anonymous
Submitted by anonymous
over 9 years

i still cant do it lol

Profile image of anonymous
Submitted by anonymous
over 9 years

thanks

Profile image of anonymous
Submitted by anonymous
about 9 years

It’s extremely frustrating to not be able to see the correct code. I’ve been stuck on 6/9 for an hour with a syntax error that I have not been able to find an answer to. Is there a place to see the correct code when stumped?

Profile image of anonymous
Submitted by anonymous
about 9 years

@Ron, I’m sure several people have posted all the answers somewhere on the internet, but usually what people do here is use the “Ask a question” button and post their code, their error message and any thoughts they have on what’s going on. Then other people read all of that and offer guidance.

Profile image of anonymous
Submitted by anonymous
about 9 years

The exercises should be created in a way that you should be able to solve them on your own but unfortunately their might be some exercises that are better than others and some warnings might not be as accurate as they should be so if you get stuck rather ask the question yourself in the Q&A or google for the concept itself instead of the answer, if you’ve understood what you are trying to do and how to do it you can skip the exercise if you want but progressing without understanding what you do might make it harder to understand further stuff. Also you can have a look at e.g. labs.codecademy.com where you can test code that you think should be running without the requirements of an exercise. Good sources are also MDN+javaScript command or stackoverflow.

Profile image of anonymous
Submitted by anonymous
about 9 years

Thank you, noted, let me check labs.codecademy.com I didn’t know of its existence.

Answer 529fa36052f863bb58000338

12 votes

Permalink

Conditions, Blocks and Semicolons

The most simple conditional statement (1) looks like this:

if(condition)
   statement;

Here statement is exactly 1 statement. In case you want an alternativ to the if you can extend it with an else (2):

if(condition)
   statement;
else
   statement2;

Again statement and statement2 are only one statement (each). But what about using more than one statement in a case? (3)

if(condition)
   statement1;
   statement2;

here statement1 would belong to the condition and statement2 would be executed without condition. (4)

if(condition)
   statement1;
   statement2;
else
   statement3;

And here it would get even worse, as the else needs to follow directly after the statement of the if or they will not be treated as connected and you get an error as an else doesn’t make sense without an if.

So how can we use more than one statement per case, what are these {} we usually use and why should we even bother about these cases mentioned above?

Well to have more than one statement per case we use the trick of working with blocks of code which start with { and end with } these blocks count as one statement regardless of the number of statements which are inside.(*)

The reason why we should have a look at this although you could be perfectly fine by using blocks all the time even if they are not necessary is that we every now an then may encounter one of the errors described above which are related to this ability.

e.g. a semicolon:

When you put a semicolon at the end of a condition, like this: if (choice1 === choice2); you are telling the interpreter to consider that as the end of your if statement. Any code following that will be processed without regard for the outcome of that if condition.

That’s pretty close, but the semicolon doesn’t end the if statement itself, it ends the statement of the if. This might be confusing, but have a look at (1) and you could see that if(condition); just means:

if(condition)
  /*empty space*/;

so the semicolon creates an empty statement by ending the “nothing” after the condition which would normaly be ignored and now the condition is either finished or an else needs to follow directly after it, but mostly it was just a mistake and it goes like this: if(condition);{...} and then you end up at the error described in (4).

Another use of this feature is that a conditional statement counts as one statement aswell, which lets us create an else if case by nesting:

if(condition)
  statement;
else
  if(condition2)
    statement2;
  else
    statement3;

could be formatted to:

if(condition)
  statement1;
else if(condition2)
  statement2;
else
  statement3;

(*) {} are used as blocks of codes for conditions and loops, functions and objects may use them in a different way.

Profile image of anonymous
Submitted by anonymous
almost 11 years

6 comments

Profile image of anonymous
Submitted by anonymous
over 10 years

Very Useful as Well… Thank you for sharing haxor

Profile image of anonymous
Submitted by anonymous
over 10 years

Thanks for sharing!

Profile image of anonymous
Submitted by anonymous
over 10 years

Thank for sharing

Profile image of anonymous
Submitted by anonymous
over 10 years

Thanking You :D

Profile image of anonymous
Submitted by anonymous
over 10 years

thanks!

Profile image of anonymous
Submitted by anonymous
almost 10 years

thank’s very much…..very helpful to me!

Answer 52373b0c80ff3316380000e7

4 votes

Permalink

Are you getting one of the errors on the list at the top of this thread but following the troubleshooting steps isn’t helping? Show us all of your code using the “Add an answer” box, tell us the EXACT error message and we’ll look into it!

Profile image of anonymous
Submitted by anonymous
about 11 years

25 comments

Profile image of anonymous
Submitted by anonymous
almost 11 years

sorry THIS is my code var balance = 20.97; if (balance<10) { console.log(balance-5)} else { console.log=(balance) }

Profile image of anonymous
Submitted by anonymous
almost 11 years

@JovyCB: Rather than trying to make console.log = (balance) just console.log(balance) – doesn’t that seem more sensible?

Profile image of anonymous
Submitted by anonymous
almost 11 years

I’m sorry but I still don’t understand. This is my code: var balance = 20.97; if (balance < 10) { console.log(balance - 5); } else { console.log(balance); }

Profile image of anonymous
Submitted by anonymous
almost 11 years

@Wanda - that looks perfect - what error message is it giving you?

Profile image of anonymous
Submitted by anonymous
almost 11 years

Oops, try again. Your code doesn’t look quite right. Check the Hint if you need help! ALSO, on the result screen it’s giving me this: RefernceError: Can’t find variable aaaaaaaaaaaaaaaa…

Profile image of anonymous
Submitted by anonymous
almost 11 years

@Wanda, the code as you’ve shown here is perfect. Unless there is some other bits that I can’t see? Try refreshing/reloading your web page. If that doesn’t work, if possible, try it in a different web browser.

Profile image of anonymous
Submitted by anonymous
over 10 years

var creditCheck = function (income) { if (creditCheck >= 100) return (“You earn a lot of money! You qualify for a credit card.”) } ; else ; { (creditCheck < 100) ; return (“Alas you do not qualify for a credit card. Capitalism is cruel like that.”) } It says right before “else” that it expected an identifier.

Profile image of anonymous
Submitted by anonymous
over 10 years

@darecode - you have several things going on there that need fixing - too many for this little comment box. Could I get you to use the green “Ask an answer button” please?

Profile image of anonymous
Submitted by anonymous
over 10 years

Im assuming you mean ask a question, and I did so,

Profile image of anonymous
Submitted by anonymous
over 10 years

@darecode - I must have been really distracted when I typed that - good thing I said “green”! Can you see your new question in the list - because I can’t. Could you try again please - or give me the link to it.

Profile image of anonymous
Submitted by anonymous
over 10 years

@darecode, thanks, I see it now.

Profile image of anonymous
Submitted by anonymous
over 10 years

Great, waiting for your answer, honestly, I’m stumped :/

Profile image of anonymous
Submitted by anonymous
over 10 years

Oops, try again. Check your if statement–it looks like you didn’t print the correct value.I got this error for1/13

Profile image of anonymous
Submitted by anonymous
over 10 years

var balance = 20.97;

// Complete the condition in the ()s on line 4 if (balance<10 ) { console.log( “balance-5”); } else { }console.log(“ balance”);

Profile image of anonymous
Submitted by anonymous
over 10 years

@Mineli, you’ve almost got it. Putting “ “ around your variables is killing their magic and turning them into plain old strings.

Profile image of anonymous
Submitted by anonymous
over 10 years

yes……..thanks…..I’ve Got it:P

Profile image of anonymous
Submitted by anonymous
over 10 years

Yay @Mineli!

Profile image of anonymous
Submitted by anonymous
over 10 years

Ohhhhh! i get it now

Profile image of anonymous
Submitted by anonymous
over 10 years

And don’t forget to refresh the page before fixing this bug, as otherwise you’ll be told hat console.log is not a function as it now contain the value of balance as you can see by using alert(console.log).

Profile image of anonymous
Submitted by anonymous
over 10 years

unexpected token else

Profile image of anonymous
Submitted by anonymous
almost 10 years

ReferenceError: Console is not defined

Profile image of anonymous
Submitted by anonymous
almost 10 years

use a lowercase c in console

Profile image of anonymous
Submitted by anonymous
over 9 years

unexpected keyword else

Profile image of anonymous
Submitted by anonymous
over 9 years

Hi nicoledille, when the JavaScript interpreter is telling you that if found an unexpected else, that is likely because you have ended your if statement before the statement was finished - likely by putting a ; where it doesn’t belong. You can see several examples of that in my original post. I can only guess at this though because you haven’t shown us your code.

Answer 5247ec47548c35eda5002195

0 votes

Permalink

Very useful - thanks!

Profile image of anonymous
Submitted by anonymous
about 11 years

2 comments

Profile image of anonymous
Submitted by anonymous
about 11 years

You’re welcome!

Profile image of anonymous
Submitted by anonymous
about 11 years

Thank you!!! Those pesky semicolons were eating me up on the if/else 1st line. Now I know why!!!

Answer 529fa53c8c1ccc73b5000359

0 votes

Permalink

@Mark: The error you explained is also caused by this only-one-statement-after-a-conditional-case-rule. At first you are absolutly right about the fact that else does not need a condition! But the error in the code is not that else has “condition” but that there are two statements on one line (without separator):

else (a == b) {
    do something different;
}

first statement is the a == b, which is a pretty pointless statement as it is just true or false and is neither stored nor printed (as said, else doesn’t expect a condition, so the () don’t show any relation to else but just increase the priority of evaluating the stuff inside, which is unnecessary as this code would follow anyway) and the second statement is the begining of the block.

So if you had used:

else (a == b) 
{
    do something different;
}

or

else (a == b); {
    do something different;
}

it would still be pointless and missleading as the code in the block would be evaluated in any case, but syntactically it would be correct.

Profile image of anonymous
Submitted by anonymous
almost 11 years

Answer 55d78a4c93767667040003da

0 votes

Permalink

var sleepCheck = function(numHours) {
    if (numHours >= 8) {
        return "You're getting plenty of sleep! Maybe even too much!";
    } else {
        return "Get some more shut eye!;
    }
};
sleepCheck(5);

SyntaxError: Unexpected token ILLEGAL

Profile image of anonymous
Submitted by anonymous
about 9 years

1 comments

Profile image of anonymous
Submitted by anonymous
about 9 years

Hi JamyangTenzin, it looks like you are missing one “

Answer 55fb2b12d3292f0a6a0002d4

0 votes

Permalink

also stuck with unexpected token pls what is wrong with this code var sleepCheck = function(numHours); if (numHours >= 8) { return “You’re getting plenty of sleep! Maybe even too much!”; } else { return “Get some more shut eye”; } sleepCheck (5);

Profile image of anonymous
Submitted by anonymous
about 9 years

1 comments

Profile image of anonymous
Submitted by anonymous
about 9 years

Hi Michaelmgbame, your very first line has the problem. When you define a function, you put all of the code that you want the function to consist of in a { block }. Instead of a { to start that block, you have put a semicolon at the end of that first line. Semicolons are for ending things, so you have ended your function right there at the end of that first line.

Answer 56093ae795e3784881000086

0 votes

Permalink

Hey, i’m not sure what’s wrong with the code. The error I’m getting is “unexpected token else”

var compare = function(choice1, choice2) { if (choice1 === choice2) { return “The result is a tie!”; } else if (choice1 === “rock”) { if (choice2 === “scissors”) { return “rock wins”; } else { return “paper wins”; } };

    else if (choice1 === "paper") {
        if (choice2 === "rock") {
            return "paper wins";
        } 
        else {
            return "scissors wins";
        }
    };

};

PS: I’ve figured it out. I only needed that final semi-colon after the last closing brace, not the ones after the else if closing brace.

Profile image of anonymous
Submitted by anonymous
about 9 years