Else/if question

Why does this code prints both sentences:

var hungerLevel = 10
if (hungerLevel > 7)
console.log (“Time to eat”)
else (hungerLevel < 7 )
console.log (“Lets eat later”)

But if I change the second “else” for an “if” it prints only one? Shouldn’t print only once sentence in both cases?

You didn’t put any opening {} for if and else, so it ignores them and prints both.

Hi @textslayer61961

The if/else statement works when :

if (the condition is true) {
   // run the code
} else {
   // everything that does not fulfill IF will fall into this ELSE category

so your question, the else condition is making the code faulty. Remove it and you’re good to go.

Remember, whatever does not comply to IF will fall into ELSE, else needs no condition to be written. Whereas, else if is another different case which you will soon learn about it along the lessons.

Hope this clarifies. :slight_smile:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.