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

Getting Started with Programming Forum

View Course

3691 points
55df2afa95e3787b9200005e_359368177
Submitted by
Judy
almost 4 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!

1171 points
5251c01cf10c60748700d891_678478070
Submitted by
Mark
almost 4 years ago

25 Comments

55df2afa95e3787b9200005e_359368177 Judy almost 4 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).

5251c01cf10c60748700d891_678478070 Mark almost 4 years ago

No problem, looks good! Thanks!

52878bf9abf821140b004c0f_270126667 chrismc1076 over 3 years ago

Thank you! That helped

528ae8ec80ff33c203000939_687421740 KhalilDaCoder over 3 years ago

Great post! I Will refer to it often!

Picture 宇峯鄭 over 3 years ago

big help!

Picture Trenton Turner over 3 years ago

you rock!!

52e129e69c4e9d1e0c001a43_575418330 MUSTAPHA OLUWATOSIN over 3 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.

52f264de548c35e7c4001d46_632637515 Anoosh Moutafian over 3 years ago

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

Ae17aa5f68af76f65aa936ab311fef3a?s=140&d=retro Ben Barber over 3 years ago

Yes! Thank you!!

530b20c1282ae342db0017f2_444155369 Alexander Scheer over 3 years ago

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

Picture Emily Owaki about 3 years ago

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

535662199c4e9ded42000e8d_750655767 Goutam Bagchi about 3 years ago

Thank You for help

C1fbcfaef94c922e341d9b5b5724782f?s=140&d=retro Appear about 3 years ago

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

1a70195376bd1bc3382df2e02d9d121b?s=140&d=retro total_tool_22 about 3 years ago

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

5139256f6a90a0ef75009600_690502710 haxor789 about 3 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.

97126265c1fa7f41f20604278961ea60?s=140&d=retro Gatho5 about 3 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.

82187589bc1c20e41092406c969226a0?s=140&d=retro George almost 3 years ago

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

53fb5a4a631fe97d2200a68a_712253049 RonandoL over 2 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.

5537c562937676a004000105_919962264 Grady Lawlor over 2 years ago

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

554f24149376769ca400049f_411154471 sweginator3000 over 2 years ago

i still cant do it lol

5534ec7095e37800a300025e_90412420 link110 over 2 years ago

thanks

658638382f2832ea60128251b5b9f025?s=140&d=retro Ron Harrington about 2 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?

55df2afa95e3787b9200005e_359368177 Judy about 2 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.

5139256f6a90a0ef75009600_690502710 haxor789 about 2 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.

55de654ce39efe9a4a000717_225845417 Fundi about 2 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
5139256f6a90a0ef75009600_690502710
Submitted by
haxor789
over 3 years ago

6 Comments

528ae8ec80ff33c203000939_687421740 KhalilDaCoder over 3 years ago

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

Picture Jiajia Montrasio over 3 years ago

Thanks for sharing!

535662199c4e9ded42000e8d_750655767 Goutam Bagchi about 3 years ago

Thank for sharing

F61bc867a1ea59e063afb0225beb6a61?s=140&d=retro kowhai9t9 about 3 years ago

Thanking You :D

531c4ea6548c35b294004dc6_825488117 vicente lee about 3 years ago

thanks!

545790739c4e9db432007fef_569770589 Mileslogic almost 3 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!

3691 points
55df2afa95e3787b9200005e_359368177
Submitted by
Judy
almost 4 years ago

25 Comments

2b1dce6ab1f5b217a0ef11182b24728d?s=140&d=retro JovyCB almost 4 years ago

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

55df2afa95e3787b9200005e_359368177 Judy almost 4 years ago

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

301ab82ee6f5671d291129da2b1bc3c0?s=140&d=retro Wanda over 3 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);
}

55df2afa95e3787b9200005e_359368177 Judy over 3 years ago

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

301ab82ee6f5671d291129da2b1bc3c0?s=140&d=retro Wanda over 3 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...

55df2afa95e3787b9200005e_359368177 Judy over 3 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.

D0d6ffbc28c388d1dadc1770be003864?s=140&d=retro darecode over 3 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.

55df2afa95e3787b9200005e_359368177 Judy over 3 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?

D0d6ffbc28c388d1dadc1770be003864?s=140&d=retro darecode over 3 years ago

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

55df2afa95e3787b9200005e_359368177 Judy over 3 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.

55df2afa95e3787b9200005e_359368177 Judy over 3 years ago

@darecode, thanks, I see it now.

D0d6ffbc28c388d1dadc1770be003864?s=140&d=retro darecode over 3 years ago

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

52f39a7a282ae3bf470021b7_65619887 Mineli over 3 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

52f39a7a282ae3bf470021b7_65619887 Mineli over 3 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");

55df2afa95e3787b9200005e_359368177 Judy over 3 years ago

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

52f39a7a282ae3bf470021b7_65619887 Mineli over 3 years ago

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

55df2afa95e3787b9200005e_359368177 Judy over 3 years ago

Yay @Mineli!

Ae17aa5f68af76f65aa936ab311fef3a?s=140&d=retro Ben Barber over 3 years ago

Ohhhhh!
i get it now

5139256f6a90a0ef75009600_690502710 haxor789 over 3 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).

Picture alaskalynn over 3 years ago

unexpected token else

Cd9e87904a098f2d49d4b47ec8252296?s=140&d=retro 13AlphaWolf13 almost 3 years ago

ReferenceError: Console is not defined

5139256f6a90a0ef75009600_690502710 haxor789 almost 3 years ago

use a lowercase c in console

7be0a445f6071082f0d63372b56eb423?s=140&d=retro nicoledille over 2 years ago

unexpected keyword else

55df2afa95e3787b9200005e_359368177 Judy over 2 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
637d33681c63e5dac53c97fbb525de88?s=140&d=retro
Submitted by
bigbelly
almost 4 years ago

2 Comments

55df2afa95e3787b9200005e_359368177 Judy almost 4 years ago

You're welcome!

2b0c92fb05c1e78662d753d6ac836f82?s=140&d=retro Brian Archer almost 4 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
5139256f6a90a0ef75009600_690502710
Submitted by
haxor789
over 3 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
6ea4724ecd7ccbb419f06653e220abab?s=140&d=retro
Submitted by
JamyangTenzin
about 2 years ago

1 Comment

55df2afa95e3787b9200005e_359368177 Judy about 2 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);

174 points
650d87047597ffa5e6004a8a5141b83c?s=140&d=retro
Submitted by
Michaelmgbame
almost 2 years ago

1 Comment

55df2afa95e3787b9200005e_359368177 Judy almost 2 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
A60fedd876872c687d8d89d50b977bdc?s=140&d=retro
Submitted by
Obinna Ugwu
almost 2 years ago