Function and If/Else


#1


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

I am getting an "Unexpected Token" error.


// Write your function below. 
// Don't forget to call your function!
var sleepCheck = function(numHours) {
    if (sleepCheck >= 8) 
    }
    {
    return "You're getting plenty of sleep! Maybe even too much!";
    }
    
    else {
        return "Get some more shut eye!";
    }

sleepCheck(10);
sleepCheck(5);
sleepCheck(8);


#2

if (sleepCheck >= 8) 
    }    <<<< move to very bottom of code
    {

#3

OK, I fixed some of my code...still getting an error for line 9 - the else statement

var sleepCheck = function(numHours) {
if (sleepCheck >= 8)

return "You're getting plenty of sleep! Maybe even too much!";
}

else;
{
    return "Get some more shut eye!";
}

sleepCheck(10);
sleepCheck(5);
sleepCheck(8);


#4

Sorry: here is all my code:

var sleepCheck = function(numHours) {
if (sleepCheck >= 8)

return "You're getting plenty of sleep! Maybe even too much!";
}

else;
{
    return "Get some more shut eye!";
}

sleepCheck(10);
sleepCheck(5);
sleepCheck(8);


#5

You have removed the token but didn't place it at the very bottom of the function body so it gets closed. Also, you removed both tokens so the if doesn't have an opening brace.

if ( ... ) {

}

Remove the semi-colon from that line.


#6

Hi @elizabeth.franklin, based on your last correction, your code still contains some missing and incorrect syntax.

To understand this, refer to the syntax below.

When assigning function, the syntax is:

var A = function (parameter) {
 
        //Run code and do something 
 
}

Notice there is one opening { and one closing }

For if/else statement, the syntax is:

if ( ... ) {
    
    //do something
    
} else {
    
    //do something else

}

Therefore, to write an if/else statement inside a function, you combine both syntax:

var A = function (parameter) {
 
    if ( .... ) {    //<=== did you miss this?
        //Do something
    } else {
        //Do something else
    }
    
}      //<==== this } closes the function

Compare the above syntax to your code, you will see the difference.
That is what @mtf has been mentioning:

} <<<< move to very bottom of code

Just make sure there are 3 opening brackets { and 3 closing brackets } for your code.

Refer the syntax above, there is no semicolon ; after else. Putting semicolon at wrong place will stop the code from running.

Hope this makes it clearer for you. :slight_smile:


#7

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