Home > Software design >  Why is my else/if statement not working right in javascript?
Why is my else/if statement not working right in javascript?

Time:03-27

I'm doing a project on codecademy, and one of the bits of code I have to write looks like this:

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 too much sleep!');
} else (actualSleepHours < idealSleepHours) {
console.log('You did not get enough sleep!');
}
};

I get an "unexpected token" error message.

The code is supposed to take the values of the getActualSleepHours and getIdealSleepHours functions/variables, compare them, and log the correct statement.

While trouble shooting, I found that deleting the curly brackets around the else statement removes the error message, and logs the else if statement, the else statement, and an 'undefined'. I don't know if that is relevant as I'm new to this.

I tried turning it into a switch statement, like:

switch {
case (actualSleepHours === idealSleepHours) :
console.log('yadda yadda');
break;

but no luck either.

Thanks for reading!

CodePudding user response:

Your "else" have an arguments, but this is not right

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 too much sleep!')
    } 
    else{
    console.log('You did not get enough sleep!')
    }
    };

Try this! Sorry for my english <3

  • Related