Trouble understanding return statement


#1

Hi, I have been doing javascript for a while, but i stil dont fully understand the return statement....for example.....in 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(10)

Why cant you replace the return statement with console.log ???
Thanks in regards


#2

return gives you something in return, so you can store whatever is return in a variable by modifying the function call a little bit:

result = sleepCheck(10);

and then log result to the console:

console.log(result);

Or you can even use console.log directly on the function call:

console.log(sleepCheck(10));

You know, when you make a test, the teacher gives you a piece of paper, and you write the answer on another piece, yes? Now, lets say the test is only one question long, and it is: 2 + 2, you write on a different piece of paper the answer (4), and give that back to me. This is how a function works, i gave you something, and you gave me the answer in return.


#3

Hello,

Please help...I've stuck in this chapter..I did exactly like the previous algorithm:

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

but it doesn't work..it says: "Ops, tente outra vez. It looks like sleepCheck() isn't returning "You're getting plenty of sleep! Maybe even too much!" when numHours is 10. Check your if / else syntax and whether you're using the correct comparison operator."..Please help me find the error..Thanks in advance.


#4

the string should be an exact match, you should return:

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

you return:

return "You are getting plenty of sleep! Maybe even too much!";

#5

ok..got it..it should be " You're". Thanks.


#6

rite kk.....so can u please explain how this code works...
and how the input numHours is processed to give a output
statement


#7

Already did? Guess i just copy paste my earlier answer:
return gives you something in return, so you can store whatever is return in a variable by modifying the function call a little bit:

result = sleepCheck(10);

and then log result to the console:

console.log(result);

Or you can even use console.log directly on the function call:

console.log(sleepCheck(10));

You know, when you make a test, the teacher gives you a piece of paper, and you write the answer on another piece, yes? Now, lets say the test is only one question long, and it is: 2 + 2, you write on a different piece of paper the answer (4), and give that back to me. This is how a function works, i gave you something, and you gave me the answer in return.