JavaScript Conditional Statements – Become an expert in its implementation!

Moving ahead in our JavaScript tutorial series, today, we will discuss the topic of Conditional Statements in JavaScript. There are various methods to produce the same output and in this article we will go through all of them and try to determine the best approach for a particular situation. This tutorial will cover if, if..else, else if and switch statements. Further, we will create a program for the ternary operator that we saw in DataFlair’s tutorial on JavaScript Operators. Later on, we will create a program that will help you calculate your grade.

Before we move on with the different types of conditional statements, let’s first understand what they actually are with the help of a real-life example.

We all have been in a situation where you only get your favorite toy when you finish your homework. If you don’t, you face punishment. The result you get is based on the condition of whether or not you finished your work. These are similar to how conditional statements work. You continue with your program after checking what the condition says. This is very helpful when you want to execute different statements for different situations.

Now let’s start with the tutorial on JavaScript conditional statements.

Stay updated with the latest technology trends while you're on the move - Join DataFlair's Telegram Channel

JavaScript Conditional Statements

Now that you know what conditional statements are, we are going to learn about the different conditional statements that JavaScript provides. We really want you to run these codes as you learn them. This will tell you where you are having trouble in understanding code. And remember, in programming, you need to run all the codes yourself to gain command on them. Practice as much as you can so you can become confident in these codes.

Let’s take a look at different conditional statements in JavaScript given below:

1. if Statement

if statement - JavaScript Conditional Statements

We use an if statement when you want to check only a specific condition. ‘if’ is a JavaScript keyword that tells the JavaScript interpreter that you are about to use a conditional statement. The statements inside an if statement will only execute if the condition is true.

The syntax for an if statement is as follows:

if (condition)
{
  //statements to be executed if true
}

You can add multiple if statements in your program, as shown in the code. JavaScript interpreter will check every if statement for its condition.

Code:

<html>
  <body>

    <script>
      var password = prompt("Enter your password."); //shows a prompt on your browser with the following text and asks for reply
      if (password == 'DataFlair'){ //checks if password is correct
        document.write("Welcome to DataFlair"); //if password is correct
      }
      if (password != 'DataFlair'){ //checks if password is incorrect
        document.write("Access Denied"); //if password is incorrect
      }
    </script>

  </body>
</html>

Screenshot:

ifstatement

Prompt (If the password is correct):

if prompt1

Output:

if op1

Prompt (If the password is incorrect):

if prompt2

Output:

if op2

After the prompt appears in the browser, if we enter the correct password “DataFlair”, we can log in. If we don’t, the browser will deny my access, just like in the second output.

2. Ternary Operator

As we discussed in our previous tutorial on JavaScript operators, the ternary operator is a special JavaScript operator. It operates on three operands to produce the result. This operator works as an alternative for a single if statement. But you should only use it for simple problems. The if statement avoids confusion and reduces the possibility of error in a complex program.

The syntax for a ternary operator is as follows:

condition? true: false;
Variable = condition? true: false;

We don’t always need to store the result in a variable. But if we want to use it later in our code, it is important that we store the value in a variable. If the condition we check is true, variable will store the true operand. If not, it will store the false operand of the code.

Code:

<html>
      <body>

            <script>
                    var password = prompt("Enter your password."); //shows a prompt on your browser with the following text and asks for reply
                    var msg = (password == 'DataFlair') ? 'Welcome to DataFlair' : 'Access Denied'; //checks for the condition
                    document.write(msg); //prints the output
            </script>

      </body>
</html>

Screenshot:

ternary statement

Prompt (If the password is correct):

ternary statement prompt

Output:ternary statement op

For a better understanding, you must explore our blog on JavaScript Variables

3. if…else Statement

ifelsestatement - JavaScript Conditional Statements

This is another method to produce the same output as with if statements and the ternary operator. We use if…else statements for this purpose. The interpreter checks if the condition is true. If yes, then the statements inside the if block is executed and if not, the else block is executed. Unlike in if statements as in the example above, we don’t need to specify any condition inside an else statement.

else is always used with if statements. The syntax for an if…else statement is as follows:

if (condition)
{
  //code if condition is true
}else{
  //code if condition is false
}

Code:

<html>
  <body>

    <script>
      var password = prompt("Enter your password."); //shows a prompt on your browser with the following text and asks for reply
      if (password == 'DataFlair'){ //checks if password is correct
        document.write("Welcome to DataFlair"); //if password is correct
      }
      else{
        document.write("Access Denied"); //if password is incorrect
      }
    </script>

  </body>
</html>

Screenshot:

if.else

Output (If the password is correct):

if prompt2

Output:

if.else op1

Excellent! Now you know how to use these basic conditional statements in your program. We have a task to complete now. Remember we talked about creating your grade sheet based on your marks? You’re wondering how to do that, right? We will do it with the help of either nested if…else statements or if…else if…else statements.

Suppose you scored 400 out of 500 in the examination. We have to calculate the grade as per the following table:

PercentageGradeRemark
> 90 A+Outstanding
< 90 and > 80AExcellent
< 80 and > 70BVery good
< 70 and > 60CGood
< 60 and > 50DCan do better
< 50ETry harder

These statements are going to modify our flowchart a bit. Now we have to check multiple conditions at once to proceed.

Did you check our blog on Latest JavaScript Applications?

4. Nested if…else Statements

nested if else - JavaScript Conditional Statements

This is a method to check multiple statements. But this is not always an ideal one. You should be very careful in using these statements. Nested if…else statements mean that there are if…else statements inside an if or an else statement.

The syntax for these statements will be something like this:

if (condition1)
{
  ...
  if (condition2)
  {
    // code if both conditions are true
  }else{
    //code if condition1 is true but condition2 is false
  }
}else{
  //code if condition1 is false
}

Or

if (condition1)
{
  //code if condition1 is true

}else{
  ...
  if (condition2)
  {
    // code if condition1 is false but condition2 is true
  }else{
    //code if both conditions are false
  }
}

Let’s calculate our grade with these statements.

Code:

<html>
  <body>

    <script>
      var marks = prompt("DataFlair: Enter your marks (out of 500)"); //asks for your marks
      var percentage = marks / 500 * 100; //calculates percentage
      if (percentage > 90) {
        document.write("Your percentage is: A+"); //case1
      }else{
        if (percentage > 80) {
          document.write("Your grade is: A"); //case2
        }else{
          if (percentage > 70) {
            document.write("Your grade is: B"); //case3
          }else{
            if (percentage > 60) {																																																																																													 
                                                     document.write("Your grade is: C"); //case4
            }else{
              if (percentage > 50) {																							 
                                                     document.write("Your grade is: D"); //case5
              }else{
                                                     document.write("Your grade is: E"); //case6
              }
            }
          }
        }
      }
    </script>

  </body>
</html>

Screenshot:

nested if.else

Prompt:

nested if.else prompt - JavaScript Conditional Statements

Output:

nested if.else op - JavaScript Conditional Statements

5. if…else if… else Statements

if else if else statement

We got the desired output from the previous technique but it wasn’t very efficient, don’t you think so? You have to check so many conditions and it might be possible that an error occurs. Your complete code will be useless with a single mistake. You want a better option for this task. One solution is to use if…else if…else statements. The interpreter will check the if condition first. If it is true, the if block runs; if false, it will move onto the else if condition. This checks if the condition is true for the second condition but false for the first one. This process continues for all the else if statements. If none of the conditions is true, the code in the else block is run.

The syntax for this technique is as follows:

if (condition1)
{
  //code if condition1 is true
}else if (condition2)
{
  //code if condition2 is true
}
...
else if (conditionN)
{
  //code if conditionN is true
}else{
  //code if all above conditions are false
}

Code:

<html>
  <body>

    <script>
      var marks = prompt("DataFlair: Enter your marks (out of 500)"); //asks for your marks
      var percentage = marks / 500 * 100; //calculates percentage
      if (percentage > 90) {
        document.write("Your percentage is: A+"); //case1
      }else if (percentage > 80) {
        document.write("Your percentage is: A"); //case2
      }else if (percentage > 70) {
        document.write("Your percentage is: B"); //case3
      }else if (percentage > 60) {
        document.write("Your percentage is: C"); //case4
      }else if (percentage > 50) {
        document.write("Your percentage is: D"); //case5
      }else{
        document.write("Your percentage is: E"); //case6
      }
    </script>

  </body>
</html>

Screenshot:

if-else-if-else - JavaScript Conditional Statements

Output:if-else-if-else-output - JavaScript Conditional Statements

This is better. We have the same output as before, but now the code is easier to read and understand.

6. switch Statements

conditional statement switch

We also have a special set of conditional statements that are very helpful when we want to execute code based on a specific condition. These are the switch statements. We use the keywords switch, case, and break for these statements. The condition of whichever case is true, that block executes.

The syntax for these statements is like this:

switch (expression)
{
  case 1: //code executed if the expression evaluates to 1
        break;
        case 2: //code executed if the expression evaluates to 2
        break;
        ...
        case N: //code executed if the expression evaluates to N
        break;
        default: //code executed if none of the cases works
}

The switch keyword tells the interpreter that the following code is for switch statements. It executes on the basis of the value calculated by the expression. If none of the cases satisfies the expression, default case executes. We recommend you to use this case in every switch case. break is an important keyword in these statements. These help the interpreter to break out of the switch block. If you don’t add this keyword after every case, the interpreter will check all other switch cases, even after one of the cases has been satisfied.

Code:

<html>
  <body>

    <script>
      var alphabet = prompt("DataFlair says Enter an alphabet"); //asks for an alphabet
      switch (alphabet)
      {
        case 'a': document.write("Vowel a");
          break; //breaks out of switch block if case 'a' is true
        case 'A': document.write("Vowel A");
          break;
        case 'e': document.write("Vowel e");
          break;
        case 'E': document.write("Vowel E");
          break;
        case 'i': document.write("Vowel i");
          break;
        case 'I': document.write("Vowel I");
          break;
        case 'o': document.write("Vowel o");
          break;
        case 'O': document.write("Vowel O");
          break;
        case 'u': document.write("Vowel u");
          break;
        case 'U': document.write("Vowel U"); //prints vowel with its name
          break;
        default: document.write("Not a vowel"); //returns not a vowel
      }
    </script>

  </body>
</html>

Screenshot:

switch - JavaScript Conditional Statements

Output (if I enter u in the prompt):

switch prompt - JavaScript Conditional Statements

Output:
switch op1 - JavaScript Conditional Statements

Output (if I enter d in the prompt):

switch op2 - JavaScript Conditional Statements

Summary

Here we come to the end of our tutorial on JavaScript conditional statements. In this article, we learned about the various conditional statements. The concept of conditional statements is common for all the programming languages, including Java. Only syntax changes when you switch between different programming languages. We hope you practiced these codes with me as practicing is the key to understanding programming.

Now, you must go through our next article on JavaScript Functions

Any queries or feedback from your side? Share them in the comment section below.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.