ES6 - if…else Statement



An if can be followed by an optional else block. The else block will execute if the Boolean expression tested by if evaluates to false.

Following is the syntax.

if(boolean_expression) {
   // statement(s) will execute if the Boolean expression is true
} else {
   // statement(s) will execute if the Boolean expression is false
}

Flowchart

if else Statement

The if block guards the conditional expression. The block associated with the if statement is executed if the Boolean expression evaluates to true. The if block may be followed by an optional else statement. The instruction block associated with the else block is executed if the expression evaluates to false.

Example: Simple if…else

var num = 12;
if (num % 2 == 0) {
   console.log("Even");
} else {
   console.log("Odd");
}

The above example prints whether the value in a variable is even or odd. The if block checks the divisibility of the value by 2 to determine the same.

The following output is displayed on successful execution of the above code.

Even
Advertisements