Conditional Statements


JavaScript conditional statements are used to perform various tasks based on different conditions.

JavaScript includes following forms of conditional statements:

1. if statement
2. else statement
3. else if statement
4. switch statement


if Statement

The if statement is used when we want to execute some statements when the specified condition is true.

Syntax:

    if (condition)
    {
        statements to be executed if the condition is true
    }    


Example:

    if(10 < 20)
    {
        alert(“10 is less than 20”);
    }

Note: curly braces { } are not required when if block contains only a single line to be execute.



else Statement

The else statement is used to execute the statements when the condition specified in if statement is false.

Syntax:

    if (condition)
    {
        statements to be executed if the condition is true
    }
    else
    {
        statements to be executed if the condition is false
    }


Example:

    if (20 < 15)
    {
        alert(“20 is less than 15”);
    }
    else
    {
        alert(“20 is not less than 15”);
    }    


else if Statement

The else if statement is used to execute the statements when condition specified in the above if statement is false.

Syntax:

    if (condition1)
    {
        statements to be executed when condition1 is true
    }
    else if (condition2)
    {
        statements to be executed when above if condition is false
    }    


Example:

    if (15 < 10)
    {
        alert(“15 is less than 10”);
    }
    else if (15 < 20)
    {
        alert(“15 is less than 20”);
    }    



switch Statement

The switch statement is used when we want to execute one of the multiple code blocks based on the return value of a specified expression.

The break keyword is used to stop the execution and exit from the switch.

Syntax:

    switch (expression)
    {
        case 1: //code to be executed
                break;
        case 2: //code to be executed
                break;
        case n: //code to be executed
                break;
        default: //code to be executed if none of the above case is true
    }


Example:

    switch (2)
    {
        case 1: alert(“case 1 is executed”);
                break;
        case 2: alert(“case 2 is executed”);
                break;
        default: alert(“default case is executed”);
    }