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.
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:
-
else if
statements are optional. What you need isif
andelse
like in the first example -
else if
statements always go betweenif
andelse
statements - You can have as many
else if
statements as possible - Donβt use
if else
in place ofelse if
1 Like