Why am I getting undefined?

I’m getting the correct answer but it is followed by undefined. Code attached.

const getSleepHours = (day) => {
  if (day === "monday") {
    return 0;
  } else if (day === "tuesday") {
    return 8;
  } else if (day === "wednesday") {
    return 8;
  } else if (day === "thursday") {
    return 8;
  } else if (day === "friday") {
    return 8;
  } else if (day === "saturday") {
    return 8;
  } else if (day === "sunday") {
    return 8;
  } else {
    return "Error";
  }
};

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

const getIdealSleepHours = () => {
  const idealHours = 10;
  return idealHours * 7;
};

const calculateSleepDebt = () => {
  let actualSleepHours = getActualSleepHours();
  let idealSleepHours = getIdealSleepHours();
  if (actualSleepHours === idealSleepHours) {
    return console.log("You got the perfect amount of sleep!");
  } 
  if (actualSleepHours > idealSleepHours) {
   return console.log('You got ' + (actualSleepHours-idealSleepHours) + ' extra hours of sleep.')} 
  if (actualSleepHours < idealSleepHours) {
    return console.log("You should get some rest. You owe yourself " + (idealSleepHours-actualSleepHours) + " hours of sleep.")}
}
console.log(calculateSleepDebt());

console.log() returns undefined.

2 Likes

Hi,
your function calculateSleepDebt already logs to the console. No need to wrap the function call in a console.log, too. Since the function does not return anything, it logs undefined.

1 Like

I see the problem now. Thank you.

1 Like

This is a fairly common question for new coders. Usually the answer is because they are using console.log to print the return value of a function that lacks an explicit return value. In those cases, undefined is returned implicitly.

Your case is slightly different. Your function has explicit return statements, but what are you returning?

console.log is a function. We pass arguments to it, and it prints the arguments to the console, and returns undefined.

function sayHi(name) { return console.log("HI, " + name + "!"); } // the call to console.log prints the argument passed // to the console, and returns undefined // undefined will then be returned from sayHi // by the explicit return statement console.log(sayHi("Bob")); // since undefined is returned //from sayHi, this console.log prints it to the console //if we call the function without printing the return value... sayHi("Bob"); // undefined is not printed to the console
2 Likes