[Unexpected Output] When tried to define a variable

This is the quiz link. (I solved the quiz but I tried some spice and failed, and curious why is it failed so I can enlarge my understanding of functions and conditions, thanks!)

This is the code is where I have issues:

const getSleepHours = day => {
  let slept;
  if(day === 'monday')
  slept = 7;
  console.log('Slept for ' + slept + ' hours');
  if(day === 'tuesday')
  slept = 8;
  console.log('Slept for ' + slept + ' hours');
  if(day === 'wednesday')
  slept = 9;
  console.log('Slept for ' + slept + ' hours');
  if(day === 'thursday')
  slept = 4;
  console.log('Slept for ' + slept + ' hours');
  if(day === 'friday')
  slept = 5;
  console.log('Slept for ' + slept + ' hours');
  if(day === 'saturday')
  slept = 10;
  console.log('Slept for ' + slept + ' hours');
  if(day === 'sunday')
  slept = 12;
  console.log('Slept for ' + slept + ' hours');
}

//Controls first function
getSleepHours('monday');

What I tried to do?

I tried to use a dynamic variable to assign when I call the days because I wanted to use that variable to use to sum up all the hours I slept during the week whenever I call a function, on the side, I wanted to print a text instead of using just a return method to get a bland number.

What happened?

When I called the function

getSleepHours(‘monday’);

Output was:

> Slept for 7 hours
> Slept for 7 hours
> Slept for 7 hours
> Slept for 7 hours
> Slept for 7 hours
> Slept for 7 hours
> Slept for 7 hours

My question:

Why is it printing Monday 7 times? Is it because there are 7 if functions? If so, why? If other conditions are also being executed, why are they not being executed within their respective assigned inputs like 8, 9, 4, etc?

It is because you are not using curly braces to define the block of code for the if statement. It should look like this:

if(day === 'friday') {
     slept = 5;
     console.log('Slept for ' + slept + ' hours');
}
2 Likes