This forum is now read-only. Please use our new forums at discuss.codecademy.com.

3701 points

Submitted by
Judy
over 6 years ago

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?


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!

1265 points

Submitted by
Mark
over 6 years ago

25 Comments

Judy over 6 years ago

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).

Mark over 6 years ago

No problem, looks good! Thanks!

chrismc1076 over 6 years ago

Thank you! That helped

KhalilDaCoder over 6 years ago

Great post! I Will refer to it often!

宇峯鄭 over 6 years ago

big help!

Trenton Turner over 6 years ago

you rock!!

MUSTAPHA OLUWATOSIN over 6 years ago

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.

Anoosh Moutafian over 6 years ago

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

Ben Barber over 6 years ago

Yes! Thank you!!

Alexander Scheer over 6 years ago

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

Emily Owaki about 6 years ago

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

Goutam Bagchi almost 6 years ago

Thank You for help

Appear almost 6 years ago

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

total_tool_22 almost 6 years ago

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

haxor789 almost 6 years ago

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.

Gatho5 almost 6 years ago

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.

George over 5 years ago

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

RonandoL over 5 years ago

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.

Grady Lawlor about 5 years ago

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

sweginator3000 about 5 years ago

i still cant do it lol

link110 about 5 years ago

thanks

Ron Harrington almost 5 years ago

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?

Judy almost 5 years ago

@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.

haxor789 almost 5 years ago

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.

Fundi almost 5 years ago

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


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.

3324 points

Submitted by
haxor789
over 6 years ago

6 Comments

KhalilDaCoder over 6 years ago

Very Useful as Well... Thank you for sharing haxor

Jiajia Montrasio about 6 years ago

Thanks for sharing!

Goutam Bagchi almost 6 years ago

Thank for sharing

kowhai9t9 almost 6 years ago

Thanking You :D

vicente lee almost 6 years ago

thanks!

Mileslogic over 5 years ago

thank's very much.....very helpful to me!


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!

3701 points

Submitted by
Judy
over 6 years ago

25 Comments

JovyCB over 6 years ago

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

Judy over 6 years ago

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

Wanda over 6 years ago

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);
}

Judy over 6 years ago

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

Wanda over 6 years ago

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...

Judy over 6 years ago

@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.

darecode over 6 years ago

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.

Judy over 6 years ago

@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?

darecode over 6 years ago

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

Judy over 6 years ago

@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.

Judy over 6 years ago

@darecode, thanks, I see it now.

darecode over 6 years ago

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

Mineli over 6 years ago

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

Mineli over 6 years ago

var balance = 20.97;

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

Judy over 6 years ago

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

Mineli over 6 years ago

yes........thanks.....I've Got it:P

Judy over 6 years ago

Yay @Mineli!

Ben Barber over 6 years ago

Ohhhhh!
i get it now

haxor789 over 6 years ago

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).

alaskalynn about 6 years ago

unexpected token else

13AlphaWolf13 over 5 years ago

ReferenceError: Console is not defined

haxor789 over 5 years ago

use a lowercase c in console

nicoledille about 5 years ago

unexpected keyword else

Judy about 5 years ago

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.


0 votes

permalink

Very useful - thanks!

258 points

Submitted by
bigbelly
over 6 years ago

2 Comments

Judy over 6 years ago

You're welcome!

Brian Archer over 6 years ago

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


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.

3324 points

Submitted by
haxor789
over 6 years ago


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

92 points

Submitted by
JamyangTenzin
almost 5 years ago

1 Comment

Judy almost 5 years ago

Hi JamyangTenzin, it looks like you are missing one "


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);

176 points

Submitted by
Michaelmgbame
over 4 years ago

1 Comment

Judy over 4 years ago

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.


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.

275 points

Submitted by
Obinna Ugwu
over 4 years ago