Return vs. console.log (12/13)


#1

In an earlier exercise return was described as being used when you want to "return" a value without printing it to the console, and console.log for when you do want to print to the console (which is easy enough to follow). In this exercise however, "return" is used to print a message to the console, I don't understand. Seems like a misuse of the "return" command.


#2

Hi @cbcblades

Hopefully this post will not be too long winded and basic but will answer your question; just to try and ensure nothing gets missed ex 12 solution can be explained something like 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!");
        }
};

var sleep = sleepCheck(5);
console.log(sleep);
console.log(sleepCheck(5));

With that in mind then we should alter our understanding of the keyword return from

"described as being used when you want to "return" a value without printing it to the console"

to something more like; return is used to return a value and assign a value to the variable that was declared when calling the function. (This is a loose description but fits the bill for this exercise =)
So lets focus on the section var sleep = sleepCheck(5): Just how we assign values to any other variable, we are assigning the return value of the function sleepCheck to the variable sleep. Essentially, in a simple term sleep is now equal to what ever that function returned.

We then use this in the console.log() statement, that follows that variable declaration to print out, console.log(sleep); and that is what causes the print out.
A shorter form of that can just as easily be written as console.log(sleepCheck(5));.

Hopefully that helps a little, and you can feel free to post your own code if you need anything else clearing up, and someone will try to answer as soon as they can. =)

Cheers,
Michael