Search code examples
javascriptfunctionswitch-statementconsole.logarrow-functions

Why the console.log prints to the console "undefined" when I try to add some results in the function?


I try to add getSleepHours() in the const getActualSleepHours() to have a sum. But the console.log prints undefined and I don't know what I'm doing wrong. Could anyone help me?

const getSleepHours = day => {
  switch(day) {
    case 'monday':
      return 8;
      break;
    case 'tuesday':
      return 8;
      break;
    case 'wednesday':
      return 9;
      break;
    case 'thursday':
      return 9;
      break;
    case 'friday':
      return 7;
      break;
    case 'saturday':
      return 10;
      break;
    case 'sunday':
      return 9;
      break;
   }    
  };
   const getActualSleepHours = () => {
     getSleepHours('monday') +
     getSleepHours('tuesday') +
     getSleepHours('wednesday') +
     getSleepHours('thursday') +
     getSleepHours('friday') +
     getSleepHours('saturday') +
     getSleepHours('sunday');
           
     
     
  };
const getIdealSleepHours = () => {
  const idealHours = 8.5;
  return idealHours * 7;
};
console.log(getActualSleepHours());
console.log(getIdealSleepHours());


Solution

  • You're not returning anything in your getActualSleepHours function. Get rid of the braces so it goes from

    const getActualSleepHours = () => {
        getSleepHours("monday") +
        getSleepHours("tuesday") +
        getSleepHours("wednesday") +
        getSleepHours("thursday") +
        getSleepHours("friday") +
        getSleepHours("saturday") +
        getSleepHours("sunday");
    };
    

    to

    const getActualSleepHours = () =>
        getSleepHours("monday") +
        getSleepHours("tuesday") +
        getSleepHours("wednesday") +
        getSleepHours("thursday") +
        getSleepHours("friday") +
        getSleepHours("saturday") +
        getSleepHours("sunday");