If Else and Else If Statements

Hi! Newbie here. I just want to ask: What is the major difference between if else and else if statement? What is the proper way of using them? Thank you. :slightly_smiling_face:

If/Else indicate an if statement followed by an else statement:

if (condition) {
   ...
} else {
   ...
}

else if statements are a specific type of statement, which can be put only after an if statement, so like:

if (condition1) {
   ...
} else if (condition2) {
   ...
} 

you can put as many else if statements as needed.

You can create an if/else if/else chain starting with an if statement, followed by as many else if statements as needed and then one else statement to close

2 Likes

Let me illustrate with an example.

Use of if else


// Let us guess  allyza.fabellar's age

let age = 30;

if( age < 18){
     console.log( "She is a child")
} else{
     console.log( "She is an adult")
}

In the code above She is an adult will be console.logged
Use of if, else if and else


// Let us guess  allyza.fabellar's age

let age = 80;

if( age < 18){
     console.log( "She is a child")
}
else if (age >= 18 && age < 35){
     console.log( "She is a youth")
} 
else if (age >= 35 && age < 50){
     console.log("She is middle aged")  // I don't know what middle aged means
}else{

     console.log("She is   elderly")
}

In the code above She is elderly will be console.logged
NOTE:

  1. else if statements are optional. What you need is if and else like in the first example
  2. else if statements always go between if and else statements
  3. You can have as many else if statements as possible
  4. Don’t use if else in place of else if
1 Like

Got it! Thank you so much @ieahleen @nibble for sharing your knowledge. I understand it clearly now :grin: