“elseif” syntax in JavaScript

“elseif” syntax in JavaScript

Is this correct?
if(condition)
{

}
elseif(condition)
{

}
else
{

}

Solutions/Answers:

Solution 1:

JavaScript’s elseif is in the format “else if”, e.g.:

if (condition) {

} else if (other_condition) {

} else {

}

Solution 2:

Just add a space:

if (...) {

} else if (...) {

} else {

}

Solution 3:

You could use this syntax which is functionally equivalent:

switch (true) {
  case condition1:
     //e.g. if (condition1 === true)
     break;
  case condition2:
     //e.g. elseif (condition2 === true)
     break;
  default:
     //e.g. else
}

This works because each condition is fully evaluated before comparison with the switch value, so the first one that evaluates to true will match and its branch will execute. Subsequent branches will not execute, provided you remember to use break.

Note that strict comparison is used, so a branch whose condition is merely “truthy” will not be executed. You can cast a truthy value to true with double negation: !!condition.

Solution 4:

Actually, technically when indented properly, it would be:

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

There is no else if, strictly speaking.

Related:  Object oriented javascript with prototypes vs closures

(Update: Of course, as pointed out, the above is not considered good style.)

Solution 5:

if ( 100 < 500 ) {
   //any action
}
else if ( 100 > 500 ){
   //any another action
}

Easy, use space

Solution 6:

Conditional statements are used to perform different actions based on different conditions.

Use if to specify a block of code to be executed, if a specified condition is true

Use else to specify a block of code to be executed, if the same condition is false

Use else if to specify a new condition to test, if the first condition is false