With or without else *QUESTION*

What is the difference between using else and not using else in an if statement? Doesn’t it give you the same thing if you don’t type else? Sorry I am still on basics of javascript so idk much.

!

@khleb, think it another way, what will you do-
if your teacher does not come to the class room?
All day and night will you stay at the class room or will leave?
So, you decide, if your teachers attend the class room you will stay there, else you will leave

yes, but wouldn’t the code return no even if there wasn’t an else statement? Are you saying it is just better to include else?

TL;DR the correct answer is what ever makes your code easier to read and maintain

cleanliness and readability should be your priority in your code

that being said, i think it was in a book called Clean Code where the author says its better to leave out else and use the if statement as the alternative result

eg.

let isConnected = true;

testConnection(){
    if (!isConnected) {
        console.log('failed to connect')
        return
    }
    console.log('connection successful')
}
1 Like

most of the cases you will get the output you want, but in complex mode as your code has multiple conditions it won’t give you the expected output. So, practice of using else will help you to find out what’s happening there.
look at this code

var a=2;

if(a==2){
  console.log("condition meets") 
  }

but if you make a=3, it won’t print anything, in simple cases you can find out that it does not meet the condition, but when your code grows you can’t find out the problem where the code fails, now see this code

var a=2;

if(a==3){
  console.log("condition meets")
  } else{
    console.log("condition does not meet for var a")
    }

anyhow if you change the vale of var a, then the code will give the actual issue what happened there. When you’ll get a clear concept, you will understand where/ when you need to use else, where/when not, it totally depends on you

2 Likes

In your example, you will get two messages logged, which will be very confusing. Clever code is not the same thing as clear code.

if (true) {
  console.log("This will happen");
} else {
  console.log("This will happen instead");
}

vs

if (true) {
  console.log("This will happen");
}
console.log("This will also happen");

There is a time and a place for using only an if vs using an if-else.

If the code needs to execute only one of two things (or a few things) use an if else (or a switch).

If you only need to guard a single thing, use an if.

The code in the original post works because the if clause returns. This is the exception to my two cases above.

Edit: ahh, ninja edit from you while I typed!

2 Likes