Funtions


#1

This is the task I have to do.....

Functions & if / else

An especially useful application of reusable code is if/else statements. These can be very wordy, and a pain to type repeatedly.

We are going to write a function that checks how many hours of sleep a night you're getting. Inside the function will be an if/else statement. We want the function to check many different numbers of hours to see whether a person is getting enough sleep.

Instructions

  1. Write a function named sleepCheck that takes the parameter numHours
  2. Inside the function, write an if statement where if the number of hours of sleep is greater than or equal to 8, the computer will return "You're getting plenty of sleep! Maybe even too much!";.
  3. Otherwise (else) if the number of hours of sleep is less than 8, have the computer return "Get some more shut eye!";

Then call the function with different hours of sleep
01. Call the function with 10 hours of sleep, like this: sleepCheck(10);
02. Call the function with 5 hours of sleep.
03. Call the function with 8 hours of sleep.

This is what I wrote.................

var sleepCheck = function (numHours)

if (>8)

{return ("You're getting plenty of sleep! Maybe even too much!")}

else

{return ("Get some more shut eye!")}

sleepCheck (5)

This is what it shows on the screen.........

SyntaxError: Expected '{'

HELPPPP PLZZZZZ


#2

var sleepCheck = function (numHours) //The error is here

if (>8)

{return ("You're getting plenty of sleep! Maybe even too much!")}

else

{return ("Get some more shut eye!")}

sleepCheck (5)

You forgot to put a { in the spot I marked (and at the end of the function). Also, you seem to have made a typo in your If statement. The revised 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); //you might want to add a semicolon too

#3

After your first line,
var sleepCheck = function (numHours)
open up a curly brace, {, on the end like so:
var sleepCheck = function (numHours) {
This is opening up your function so that you can describe the purpose of it.
After that, make sure that you indent your if statement and write
if(numHours > 8)
Here you will use ANOTHER curly brace, {.
if(numHours > 8) {
Make sure you indent again so that you can write what the if statement will do.
Your next line will look like
return "You're getting plenty of sleep! Maybe even too much!"
}
Then CLOSE your braces using the other half of the pair like I did above.
Also, you want to call all three of the hours inside of the sleepCheck function like you did with 5.

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


#4

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