else statement

The else construct defines a code block that will be executed if the condition is false in the if statement.

Syntax

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

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

Example

Let's check if the variable value is greater than zero or not:

javascriptlet test = -1;

if (test > 0) {
  alert('+++');
} else {
  alert('---');
}

Example

The if-else constructs can be nested in each other in an arbitrary way:

javascriptlet num = 3;

if (num >= 0) {
  if (num <= 5) {
    alert('less than or equal to 5');
  } else {
    alert('greater than 5');
  }
} else {
  alert('less than zero');
}

See also

  • the if statement
    that sets a condition
  • the elseif statement
    that sets a condition
  • the switch statement
    that sets a condition