else if statement

The construction else if is simultaneously the else statement and the following if condition.

Syntax

javascriptif (logical expression 1) {
  /*
    a code located here will be executed
    if the logical expression 1 is true
  */
} else if (logical expression 2) {
  /*
    a code located here will be executed
    if the logical expression 2 is true
  */
} else {
  /*
    a code located here will be executed
    if the logical expression 2 is false
  */
};

If there is only one expression in curly braces, these curly braces can be omitted.

Example

Let's check whether the number 1, 2 or 3 is stored in the variable and display the corresponding value:

javascriptlet num = 1;

if (num == 1) {
  alert('value1');
} else if (num == 2) {
  alert('value2');
} else if (num == 3) {
  alert('value3');
} else {
  alert('unknown value');
};

See also

  • the if statement
    that sets a condition
  • the else statement
    that sets an opposite condition