Learn Javascript Sleep Debt Caclculator

When you ask a question, don’t forget to include a link to the exercise or project you’re dealing with!
https://www.codecademy.com/courses/introduction-to-javascript/projects/sleep-debt-calculator

I was able to get farther in this exercise by using the syntax template first. I received the following error message however:

/home/ccuser/workspace/sleep-debt-calculator/sleepDebtCalculator.js:36
if (actualSleepHours === idealSleepHours) { console.log(“You got the perfect amount of sleep!”)
^

ReferenceError: actualSleepHours is not defined
at Object.

Why would it say it is not defined? I clearly set it equal to a function call that works!

function getSleepHours(day) {
  if(day === 'monday') { 
    return 8;
  } 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 "invalid entry please choose a day of the week"
  }
}

const getActualSleepHours = () => 
getSleepHours('monday') + getSleepHours('tuesday') + getSleepHours('wednesday') + getSleepHours('thursday') + getSleepHours('friday') + getSleepHours('saturday') + getSleepHours('sunday');
// implicit return is without the curly braces. Can also use return in the beginning of the function to get the calcluation. 

console.log(getActualSleepHours())

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

const calculateSleepDebt = () => {
  const actualSleepHours = getActualSleepHours();
  const idealSleepHours = getIdealSleepHours(); 
}

if (actualSleepHours === idealSleepHours) { console.log("You got the perfect amount of sleep!")
} else if(actualSleepHours > idealSleepHours) { console.log("You got more hours of sleep than needed")
} else if(actualSleepHours < idealSleepHours) { console.log("You got less hours of sleep than needed")
} else {
  console.log("Error! Something went wrong, check your code."); 
}
// I used the function itself

Hey there,
the variables actualSleepHours and idealSleepHours are only available within the scope of calculateSleepDebt. You can either move your if/else statements into that function and then call calculateSleepDebt at the end of your code. Or you move the variables actualSleepHours and idealSleepHours out of the function calculateSleepDebt and remove calculateSleepDebt entirely as there would not be use of it anymore. The first would be the cleaner way as you don’t pollute the global scope and have the variables only available on demand.

1 Like

Thank you for your fast and correct response! My code works now! It seems they teach on scope in the next lesson -___- Would have been nice to know before attempting this but oh well.

Thanks again!