I can't figure out what's wrong!


#1

https://www.codecademy.com/courses/javascript-beginner-en-6LzGd/2/4?curriculum_id=506324b3a7dffd00020bf661


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!";
}


#2

It keeps giving me a error saying that SyntaxError: Unexpected keyword 'else'
I placed the else where it needs to be as well.


#3

Your else statement is placed outside of a function so it's not a part of if-else construct nor a part of a function.. Firstly, remove semicolon from if statement then copy & paste else statement and put it back inside a function after if statement.


#4

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!";
}

I took the semicolon off the if statement and made sure the brackets were above and above the if/else statement, I'm still confused


#5

Copy & Paste this:

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!";
}
}

You removed semilicon not in the right place. I suggest you to look at my provided fixed version and compare it with yours, so next time you can spot similar errors more easily.


#6

out of curiosity why were the curly brackets above the if and below the else statement not closed?
i always thought you had to put
{ the if statement then close it }


#7

There are probably a couple of reasons to use opening/closing curly brackets.

If you need to put more than one statement inside if/else then you must use curly brackets to wrap your statements, so JavaScript will know that those statements belong inside it. Another reason is for readability, visually it's easy to see what is inside those if/else statements.

You can totally ommit curly brackets if you put just only one statement inside if/else construct.
I always use curly brackets because for me it's more readable and I don't have to remember to place those curly brackets when I need to extend my script.

In your provided code it's totally possible to ommit curly brackets because there's only one statement in if and else.

I suggest you to indent statements that are inside if/else so it's easy to make the distinction of what belongs to what.


#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.