JavaScript IF, Else, Else IF Statement Tutorial Example

JavaScript if, else, else if statement; Through this tutorial, i am going to show you what is if, else, else if statement and how to use it javaScript.

In javaScript; conditional statements are also known as decision-making statements, Which are used to making a decision and executes a block of codes based on certain conditions.

JavaScript IF, Else, Else IF Statement Example

  • Type of Type of JavaScript’s Conditional Statements
    • If statement
    • If…Else statement
    • If…Else If…Else statement

Type of JavaScript’s Conditional Statements

There are mainly three types of conditional statements in JavaScript that you can use to make decisions:

  • The if statement
  • The if…else statement
  • The if…else if….else statement

If Statement

The if statement executes a block of code if a condition is true.

Syntax
if (test condition)
{
    code to be executed if condition is true
}
Example of If Statement

Let’s take example for if statement and check only a specific condition using if statement:

<html>
<head>
  <title>IF Statments!!!</title>
  <script type="text/javascript">
    var num = prompt("Solve :- 8+5");
    if(num == 13)
    document.write("Correct answer <br />");
    if(num == 13)
    document.write("Wrong answer <br />");
  </script>
</head>
<body>
</body>
</html>

In the above example, we have used javascript popup methods to taking input from user.

If Else Statement

When the if test condition evaluates to false. Then execute else statement block of code.

Syntax
if (test condition)
{
    code to be executed if condition is true
}
else
{
   code to be executed if condition is false
}
Example of if Statement

Let’s take example for If Else statement:

<html>
<head>
  <title>IF ELSE Statments!!!</title>
  <script type="text/javascript">
    var num = 13;
    if(num == 12){  
      document.write("Execute If Statement<br />");
    }else{
      document.write("Execute Else Statement<br />");
    }
  </script>
</head>
<body>
</body>
</html>

If..Else If..Else Statement

When test multiple conditions after if statement. Then use Else If statement.

Syntax
if (test condition1)
{

code to be executed if condition1 is true

}
else if(test condition2)
{

lines of code to be executed if condition2 is true

}
else
{

code to be executed if condition1 is false and condition2 is false

}
Example of If Else If Else Statement

Let’s take example for if statement and check multiple conditions:

<html>
<head>
  <title>IF ELSE If Else Statments!!!</title>
  <script type="text/javascript">
    var num = 13;
    if(num == 12){  
      document.write("Execute If Statement<br />");
    }else if(num == 13){
      document.write("Execute Else If Statement<br />");
    }else{
      document.write("Execute Else Statement<br />");
    }
  </script>
</head>
<body>
</body>
</html>

Recommended JavaScript Tutorials

Leave a Comment