if / else errors - learn how to fix these | Codecademy (2024)

Skip to Content

This forum is now read-only. Please use our new forums! Go to forums

banner

Close banner

points

if / else errors - learn how to fix these | Codecademy (1)

Submitted by

Judy

almost 11 years

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!

points

if / else errors - learn how to fix these | Codecademy (2)

Submitted by

Mark

over 10 years

25 comments

if / else errors - learn how to fix these | Codecademy (3) Judy

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

if / else errors - learn how to fix these | Codecademy (4) Mark

over 10 years

No problem, looks good! Thanks!

if / else errors - learn how to fix these | Codecademy (5) chrismc1076

over 10 years

Thank you! That helped

if / else errors - learn how to fix these | Codecademy (6) KhalilDaCoder

over 10 years

Great post! I Will refer to it often!

if / else errors - learn how to fix these | Codecademy (7) 宇峯鄭

over 10 years

big help!

if / else errors - learn how to fix these | Codecademy (8) Trenton Turner

over 10 years

you rock!!

if / else errors - learn how to fix these | Codecademy (9) MUSTAPHA OLUWATOSIN

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.

if / else errors - learn how to fix these | Codecademy (10) Anoosh Moutafian

over 10 years

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

if / else errors - learn how to fix these | Codecademy (11) Ben Barber

over 10 years

Yes! Thank you!!

if / else errors - learn how to fix these | Codecademy (12) Alexander Scheer

over 10 years

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

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

if / else errors - learn how to fix these | Codecademy (14) Goutam Bagchi

about 10 years

Thank You for help

if / else errors - learn how to fix these | Codecademy (15) Appear

about 10 years

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

if / else errors - learn how to fix these | Codecademy (16) total_tool_22

almost 10 years

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

if / else errors - learn how to fix these | Codecademy (17) haxor789

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

if / else errors - learn how to fix these | Codecademy (18) Gatho5

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

if / else errors - learn how to fix these | Codecademy (19) George

almost 10 years

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

if / else errors - learn how to fix these | Codecademy (20) RonandoL

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.

if / else errors - learn how to fix these | Codecademy (21) Grady Lawlor

about 9 years

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

if / else errors - learn how to fix these | Codecademy (22) sweginator3000

about 9 years

i still cant do it lol

if / else errors - learn how to fix these | Codecademy (23) link110

about 9 years

thanks

if / else errors - learn how to fix these | Codecademy (24) Ron Harrington

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

if / else errors - learn how to fix these | Codecademy (25) Judy

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

if / else errors - learn how to fix these | Codecademy (26) haxor789

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

if / else errors - learn how to fix these | Codecademy (27) Christopher mlalazi

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

points

if / else errors - learn how to fix these | Codecademy (28)

Submitted by

haxor789

over 10 years

6 comments

if / else errors - learn how to fix these | Codecademy (29) KhalilDaCoder

over 10 years

Very Useful as Well… Thank you for sharing haxor

if / else errors - learn how to fix these | Codecademy (30) Jiajia Montrasio

about 10 years

Thanks for sharing!

if / else errors - learn how to fix these | Codecademy (31) Goutam Bagchi

about 10 years

Thank for sharing

if / else errors - learn how to fix these | Codecademy (32) kowhai9t9

almost 10 years

Thanking You :D

if / else errors - learn how to fix these | Codecademy (33) vicente lee

almost 10 years

thanks!

if / else errors - learn how to fix these | Codecademy (34) Mileslogic

over 9 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!

points

if / else errors - learn how to fix these | Codecademy (35)

Submitted by

Judy

almost 11 years

25 comments

if / else errors - learn how to fix these | Codecademy (36) JovyCB

over 10 years

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

if / else errors - learn how to fix these | Codecademy (37) Judy

over 10 years

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

if / else errors - learn how to fix these | Codecademy (38) Wanda

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

if / else errors - learn how to fix these | Codecademy (39) Judy

over 10 years

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

if / else errors - learn how to fix these | Codecademy (40) Wanda

over 10 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…

if / else errors - learn how to fix these | Codecademy (41) Judy

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

if / else errors - learn how to fix these | Codecademy (42) darecode

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.

if / else errors - learn how to fix these | Codecademy (43) Judy

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?

if / else errors - learn how to fix these | Codecademy (44) darecode

over 10 years

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

if / else errors - learn how to fix these | Codecademy (45) Judy

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.

if / else errors - learn how to fix these | Codecademy (46) darecode

over 10 years

http://www.codecademy.com/forum_questions/52e463bb548c355a72005f55 @AlbionsRefuge

if / else errors - learn how to fix these | Codecademy (47) Judy

over 10 years

@darecode, thanks, I see it now.

if / else errors - learn how to fix these | Codecademy (48) darecode

over 10 years

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

if / else errors - learn how to fix these | Codecademy (49) Mineli

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

if / else errors - learn how to fix these | Codecademy (50) Mineli

over 10 years

var balance = 20.97;

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

if / else errors - learn how to fix these | Codecademy (51) Judy

over 10 years

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

if / else errors - learn how to fix these | Codecademy (52) Mineli

over 10 years

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

if / else errors - learn how to fix these | Codecademy (53) Judy

over 10 years

Yay @Mineli!

if / else errors - learn how to fix these | Codecademy (54) Ben Barber

over 10 years

Ohhhhh!i get it now

if / else errors - learn how to fix these | Codecademy (55) haxor789

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

if / else errors - learn how to fix these | Codecademy (56) alaskalynn

about 10 years

unexpected token else

if / else errors - learn how to fix these | Codecademy (57) 13AlphaWolf13

over 9 years

ReferenceError: Console is not defined

if / else errors - learn how to fix these | Codecademy (58) haxor789

over 9 years

use a lowercase c in console

if / else errors - learn how to fix these | Codecademy (59) nicoledille

about 9 years

unexpected keyword else

if / else errors - learn how to fix these | Codecademy (60) Judy

about 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

votes

Permalink

Very useful - thanks!

points

if / else errors - learn how to fix these | Codecademy (61)

Submitted by

bigbelly

over 10 years

2 comments

if / else errors - learn how to fix these | Codecademy (62) Judy

over 10 years

You’re welcome!

if / else errors - learn how to fix these | Codecademy (63) Brian Archer

over 10 years

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

Answer 529fa53c8c1ccc73b5000359

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.

points

if / else errors - learn how to fix these | Codecademy (64)

Submitted by

haxor789

over 10 years

Answer 55d78a4c93767667040003da

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

points

if / else errors - learn how to fix these | Codecademy (65)

Submitted by

JamyangTenzin

almost 9 years

1 comments

if / else errors - learn how to fix these | Codecademy (66) Judy

almost 9 years

Hi JamyangTenzin, it looks like you are missing one “

Answer 55fb2b12d3292f0a6a0002d4

votes

Permalink

also stuck with unexpected token pls what is wrong with this codevar 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);

points

if / else errors - learn how to fix these | Codecademy (67)

Submitted by

Michaelmgbame

almost 9 years

1 comments

if / else errors - learn how to fix these | Codecademy (68) Judy

almost 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

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.

points

if / else errors - learn how to fix these | Codecademy (69)

Submitted by

Obinna Ugwu

over 8 years

Popular free courses

  • Free CourseLearn SQLBeginner friendly,4 Lessons In this SQL course, you'll learn how to manage large datasets and analyze real data using the standard data management language.Language Fluency
  • Free CourseLearn JavaScriptBeginner friendly,11 Lessons Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Language Fluency
  • Free CourseLearn HTMLBeginner friendly,6 Lessons Start at the beginning by learning HTML basics — an important foundation for building and editing web pages.Language Fluency

Explore full catalog

if / else errors - learn how to fix these | Codecademy (2024)
Top Articles
Latest Posts
Article information

Author: Lakeisha Bayer VM

Last Updated:

Views: 5588

Rating: 4.9 / 5 (69 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Lakeisha Bayer VM

Birthday: 1997-10-17

Address: Suite 835 34136 Adrian Mountains, Floydton, UT 81036

Phone: +3571527672278

Job: Manufacturing Agent

Hobby: Skimboarding, Photography, Roller skating, Knife making, Paintball, Embroidery, Gunsmithing

Introduction: My name is Lakeisha Bayer VM, I am a brainy, kind, enchanting, healthy, lovely, clean, witty person who loves writing and wants to share my knowledge and understanding with you.