Sleep debt calculator returns undefined at the end

Script works fine but returns undefined at the end of the output doing in vscode tho

this is the output:

Your actual sleeping hours are: 57
Your ideal sleeping hours are: 56
user got more sleep than needed
undefined

code:

const getSleepHours = (day) => {

switch (day) {

case 'Monday':

  return 8;

case 'Tuesday':

  return 7;

case 'Wednesday':

  return 9;

case 'Thursday':

  return 11;

case 'Friday':

  return 5;

case 'Saturday':

  return 8;

case 'Sunday':

  return 9;

}

};

const getActualSleepHours = () =>

getSleepHours(‘Monday’) +

getSleepHours(‘Tuesday’) +

getSleepHours(‘Wednesday’) +

getSleepHours(‘Thursday’) +

getSleepHours(‘Friday’) +

getSleepHours(‘Saturday’) +

getSleepHours(‘Sunday’);

const getIdealSleepHours = () => {

let idealHours = 8;

return idealHours * 7;

};

console.log(Your actual sleeping hours are: ${getActualSleepHours()});

console.log(Your ideal sleeping hours are: ${getIdealSleepHours()});

const calculateSleepDebt = () => {

let actualSleepHours = getActualSleepHours();

let idealSleepHours = getIdealSleepHours();

if (actualSleepHours === idealSleepHours) {

console.log('user got the perfect amount of sleep');

} else if (actualSleepHours > idealSleepHours) {

console.log('user got more sleep than needed');

} else {

console.log('user should get some rest');

}

};

console.log(calculateSleepDebt());

Hi there and welcome to the forums!

The function the way it has been set up will log the sentences to the console from within the function, and will return nothing as there is no return statement anywhere within the function. When you console.log() a function, it runs through the function and then logs to console the value that is returned. Therefore when you are running console.log(calculateSleepDebt()), it is running the function as intended, and then also logging the value returned from the function. As this is nothing, the default is undefined and hence undefined is logged to the console.

You can fix this in two ways, either you can just remove the console.log(), so the call is simply calculateSleepDebt(). Or else you can change the interior of the function such that instead of logging the text you return it from the function, for example:

if (actualSleepHours === idealSleepHours) {
   return 'user got the perfect amount of sleep'
}

Either of these will solve the problem! Hopefully that helps.

Thanks man i removed the console.log() and it worked, nice :+1:

1 Like