JavaScript If Else

JavaScript If Else is used to execute a block of statements based on a condition.

In this tutorial, we shall learn following statements related to JavaScript If Else.

  • If statement
  • If-Else statement
  • If-Else-If statement
  • Nested If-Else

JavaScript If

It is used to conditionally execute a set of statements.

ADVERTISEMENT

Syntax

if(expression){
    // set of statements
}

Explanation : If expression is true, then set of statements are executed. Else execution continues with the statements after if-statement.

Example

index.html


JavaScript If-Else

It is an extension to Javascript If statement. When the condition is false, another set of statements are executed.

Syntax

if(expression){
    // set of statements
} else{
    // another set of statements
}

Explanation : If expression is true, then set of statements are executed. Else another set of statements are executed. Either of the two sets of statements shall be executed for sure based on the condition. Execution continues with the statements after if-else statement.

Example

index.html


JavaScript If-Else-If

It is an extension to Javascript If-Else statement. Instead of a single condition, there are multiple conditions.

Syntax

if(expression){
    // set of statements
} else if(expression_2){
    // another set of statements
} else if(expression_3){
    // another set of statements
} else{
    // default set of statements
}

Explanation : In a sequential order, from top to bottom, the block of statements for which the condition is true is executed. Once the control comes across a condition that is true, rest of the else if blocks are skipped.

There could be as many number of else if blocks as required.

else block is optional. When no condition is satisfied, else is executed.

Example

index.html


JavaScript Nested If

JavaScript If statements could be nested. If statement is like any other JavaScript statement. So it could be one of the ‘set of statements’ inside another if block.

Syntax

if(expression_1){
    // set of statements
    if(expression_2){
        // another set of statements
    }
}

Explanation : If expression_1 is true, control enters the first if block and executes the set of statements. Next if condition is evaluated.

Example

index.html

Conclusion

In this JavaScript Tutorial, we have learnt about JavaScript If, JavaScript If-Else, JavaScript If-Else-If, JavaScript Nested If with Syntax and Examples.