Sleep Debt Calculator: "undefined" word appears out of the blue

Hi Guys, Selma here :smiley:

I’m working on the js functions project: Sleep Debt Calculator .

Everything went well till I decided to get a bit creative lol.

So for question 9 ; I wrote the following code:

const sleepDebt = function() {
  const idealSleepHours = getIdealSleepHours();
  const actualSleepHours = getActualSleepHours();
  const hoursDif = Math.abs(idealSleepHours - actualSleepHours);
  if (idealSleepHours === actualSleepHours) {
     return 'Right on! you got the perfect amount of sleep this week.';
   } 

  idealSleepHours > actualSleepHours? console.log(`Your sleep debt for this week is ${hoursDif} hour(s).`) : console.log(`You slept for an extra ${hoursDif} hour(s).`);
}

console.log(sleepDebt());

this logs the following:

Your sleep debt for this week is 1 hour(s).
undefined

Any idea what might have caused the “undefined” to be logged?

Note: when I use the following alternative it works fine:

//const sleepDebt = function() {
  const idealSleepHours = getIdealSleepHours();
  const actualSleepHours = getActualSleepHours();
  const hoursDif = Math.abs(idealSleepHours - actualSleepHours);
  if (idealSleepHours === actualSleepHours) {
     return 'Right on! you got the perfect amount of sleep this week.';
   } 

  idealSleepHours > actualSleepHours? console.log(`Your sleep debt for this week is ${hoursDif} hour(s).`) : console.log(`You slept for an extra ${hoursDif} hour(s).`);
//}

//console.log(sleepDebt());

Thank you all!

You are getting an undefined because you are telling it to do so :wink:

Huh, how so?

Well it happens here:
console.log(sleepDebt());

When you are calling the above mentioned code two things happen.

It runs the sleepDebt function, and then the console logs whatever sleepDebt() is returning. And since sleepDebt() is not returning anything, in this case, it logs undefined. (In this case because idealSleepHours is not equal to actualSleepHours and it fails your if statement)

So you have two options, either return strings in your function (like you do in this section

if (idealSleepHours === actualSleepHours) {
     return 'Right on! you got the perfect amount of sleep this week.';
   }

Or log all your strings inside your function and only call for sleepDebt() instead console.log(sleepDebt()).

Happy coding!

3 Likes

It works!

Thank you :smiley:

1 Like