j obe
j obe

Reputation: 2029

Is it bad to use else if instead of else in javascript?

I was wondering when writing if statements can you just use an else if and leave an else statement out of the code or use an "else if" instead of an else by adding some condition that will evaluate true.

I'm quite new to javascript so just trying to understand if it's possible but just considered bad practise.

thanks

Upvotes: 0

Views: 1824

Answers (4)

Thomas
Thomas

Reputation: 3593

or use an "else if" instead of an else

there is no such thing as an else if in JS, that are two separate statements.
This is a regular else-block containing only an if-statement, and therefore skipping the curly brackets.

if(condition) {
    //...
} else if(condition2){
    //...
} else if(condition3){
    //...
} else if(condition4){
    //...
} else {
    //...
}

is nothing else than this

if(condition) {
    //...
} else {
    if(condition2){
        //...
    } else {
        if(condition3){
            //...
        } else {
            if(condition4){
                //...
            } else {
                //...
            }
        }
    }
}

by adding some condition that will evaluate true.

Why would you want to do that? Why not just writing the code inside the else-block without the useless condition around it? (as long as it is useless)

Upvotes: 0

Jaqen H'ghar
Jaqen H'ghar

Reputation: 16804

use an "else if" instead of an else by adding some condition that will evaluate true

This is a bad practice and should be avoided.

The if...else if... statement is an advanced form of if…else that allows JavaScript to make a correct decision out of several conditions.

The syntax of an if-else-if statement is used as follows −

if (expression 1){
   Statement(s) to be executed if expression 1 is true
}

else if (expression 2){
   Statement(s) to be executed if expression 2 is true
}

else if (expression 3){
   Statement(s) to be executed if expression 3 is true
}

else{
   Statement(s) to be executed if no expression is true
}

Upvotes: 1

Stivo Maich
Stivo Maich

Reputation: 11

I think using nested else...if statement is just fine, but you should use it when required and i think it will work fine in all programming languages if syntax is correct

Upvotes: 0

Jovica Šuša
Jovica Šuša

Reputation: 622

You can use "else if" without using "else" but you shouldn't use "else if" instead of "else"(instead of an else by adding some condition that will evaluate true), use "else if" when you have some additional condition besides condition defined in "if" and use "else" when you need to cover cases when all other conditions aren't true.

Upvotes: 0

Related Questions