Home > DeveloperSection > Beginner > Implementing if --- else in Java Script

Implementing if --- else in Java Script


JavaScript JavaScript 
Ratings:
0 Comment(s)
 3781  View(s)
Rate this:

Implementing if --- else in Java Script

We can use “if—else “statements to perform an appropriate action based on condition. We can use” if—else” statement to take decision on the basis of specific condition. If statements are executed if and only if condition passed to the if statements are evaluates to true otherwise else statements are executed.

Syntax of if—else statement

If (<Boolean expression>)
{

                Statement1;
                statement2;

}

Following example demonstrate use of if---else statement

Example 1: if without else

function conditionalOperatorDemo() {

            document.write("Following example demonstrate use of if block without else. <br />");

            var res = 45;

            if (res > 0) {

                document.write("Number is positive. Condition evaluates to true. <br />");

            }

}

Output of the following code snippet is as follows

if --- else in Java Script

Example 2: if with else statement

function conditionalOperatorDemo() {

            document.write("Following example demonstrate use of if block with else. <br />");

            var res = -55;

            if (res > 0) {

                document.write("Number is positive. Condition evaluates to true. <br />");

            }

            else {

                document.write("Number is negative. Condition evaluates to false. <br />");

            }

}

Output of the following code snippet is as follows

if --- else in Java Script

Example 3: Nested if--- else statement

function conditionalOperatorDemo() {

document.write("Following example demonstrate use of nested if else block. <br />");

            var age = 45;

            if (age > 0) {

                if (age > 20 && age < 50) {

                    document.write("Your are valid for this post.");

                }

                else {

                    document.write("You are overage for this post.");

                }

            }

            else {

                document.write("Invalid age you have entered.");

            }

}

Output of the following code snippet is as follows

if --- else in Java Script


Don't want to miss updates? Please click the below button!

Follow MindStick