Edit

JS If and Else

There are following conditional statements in JavaScript that you can use to make decisions:

  • The if statement
  • The if...else statement
  • The if...else if....else statement
  • The switch...case statement

The if Statement

The if statement is used to execute a block of code only if the specified condition evaluates to true.

Syntax:-

if(condition) {
    // Code to be executed
}

Example of Code

<script>
        var a = 25;
        var b = 20;
        if(a > b) {
            document.write("a is greater than b");
        }
</script>

Output

The if...else Statement

The if...else statement allows you to execute one block of code if the specified condition is evaluates to true and another block of code if it is evaluates to false. It can be written, like this:

Syntax-:

if(condition) {
    // Code to be executed if condition is true
} else {
    // Code to be executed if condition is false
}

Example of Code

<script>
     var a = 15;
     var b = 20;
    if(a > b) {
        document.write("a is greater than b");
    }
    else{
        document.write("b is greater than a");
    }
</script>

Output

The if...else if...else Statement

The if...else if...else a special statement that is used to combine multiple if...else statements.

Syntax-:

if(condition1) {
    // Code to be executed if condition1 is true
} else if(condition2) {
    // Code to be executed if the condition1 is false and condition2 is true
} else {
    // Code to be executed if both condition1 and condition2 are false
}

Example of Code

<script>
     var a = 15;
     var b = 20;
     var c = 30 
    if(a > b) {
        document.write("a is greater than b");
    }
    else if(a > c){
        document.write("a is greater than c");
    }
    else if(b > c){
        document.write("b is greater than c");
    }
    else{
        document.write("c is greater than a and b");
    }
</script>

Output