When a developer is writing a program, there can be multiple situations when it is expected out of the program execution to follow a specific path based on certain conditions. In such circumstances, the developer uses conditional statements. You must be wondering - what is a conditional statement and How to write various Javascript conditional statements? Let's try to understand it in this article with the help of the following topics:-

  • What is a Conditional Statement?

  • Conditional Statements in JavaScript

    • How to write an If statement in JavaScript?
    • Procedure to write an If else statement in JavaScript?
    • Procedure to write an If else if statement in JavaScript?
    • How to write a Switch Case Statement in JavaScript?

What is a Conditional Statement?

Javascript has specific statements enabled in it that allow us to check a condition, like all other programming languages. And it then executes certain parts of code depending on whether the condition is true or false. Such statements are called conditional statements. Generally, the conditional statement controls the program flow as below:

  • If the condition is true - the program performs one action and
  • If the condition is false - the program performs another action as shown below:

As is evident from the above figure, if the specified condition evaluates to "true", the program will execute "Statement 1". Otherwise, it will execute "Statement 2". So depending on the output of the condition, the flow of program execution will be decided.

Workflow of Conditional Statement in JavaScript

Conditional Statements in JavaScript

JavaScript supports multiple conditional statements, and these are often called Decision Statements and If Else Statements. As learned above, every program encounters a point where a decision has to made. Based on the different decisions, you want to perform various actions.

In JavaScript, the following are the conditional statements or If Else statements are present:

  • If the statement: Specifies a condition. Execute a block of code if a specified condition is true.
  • Else statement: Execute a block of code if a specified condition is false.
  • Else if statement: Specifies another condition if the first condition is not true.
  • Switch Case Statement: It is an alternative and better version of multiple If Else If blocks.

How to write an If Conditional Statement in JavaScript?

If the statement is one of the most commonly used conditional statements in any programming language, and so is the case in JavaScript also. It works on the phenomenon that if the provided condition evaluates to true only, then the statements mentioned in the block will get executed; otherwise, it will skip that block of code. Its syntax looks like below:

Syntax:

if (condtion) {
 //code that need to be executed when the specified condition is true
}

Let's understand the working of "if" conditional statement with the help of following code snippet:

<html>

   <body>  

      Demonstrating If statement

   </br>

      <script type = "text/javascript">

            var a = 5;

            if(a>4){

               document.write("value of a is greater than 4");

            }

            document.write("</br>");

      </script>      

   </body>

</html>

Save the file with name ifStatement.html and open it in any browser (Chrome, Firefox, or IE). It should show the output as:

If conditional statement in javascript

As is evident from the above screenshot, the value of the variable "a" is 5, which is greater than 4. So the if-condition evaluates to "true" and prints the statement "value is greater than 4".

How to write If-Else Conditional Statement in JavaScript?

If else statement is another widely used conditional statement which is an extended version of If statement. It works on the phenomenon that if the provided condition evaluates to true, then the statements mentioned in the "if block" will get executed; otherwise, it will execute statements present in the "else block". Its syntax looks like below:

Syntax:

if(condition){
 //Statement need to be executed if the mentioned condition evaluates to true
} else {
 //Statement need to be executed if the mentioned condition evaluates to false
}

Let's understand the working of "if-else" conditional statement with the help of following code snippet:

<html>

   <body>  

      Demonstrating If else statement

   </br>

      <script type = "text/javascript">

            var a = 5;

            if(a%2==0){

               document.write("a is an even number");

            }else{

               document.write("a is an odd number");

            }

            document.write("</br>");

      </script>      

   </body>

</html>

Save the file with name ifElseStatement.html and open it in any browser (Chrome, Firefox, or IE). It should show the output as:  if Else Conditional Statement in Javascript

As is evident from the above screenshot, the value of variable "a" is 5, which is not divisible by 2. Therefore, the if-condition evaluates to false and prints the statement "a is an odd number".

How to write If Else If Conditional Statement in JavaScript?

If the user needs to evaluate multiple conditions in the program flow, then he/she can use an advanced version of "If Else", called "If Else If ", conditional statement.

If the given condition gets true, only then the statements mentioned in the block will execute. Else, it will go to next if condition statement if it is true, then it will execute else it will move to else block. Its syntax looks like below:

Syntax:

if(condition1) {

   //Statement need to get executed if condition 1 is satisfied

}

else if(condition2){

  // Statement need to be executed if condition 2 is satisfied

} else{

  // Statement need to get executed if any of the condition is not satisfied

}

Let's understand the working of "if-else-if" conditional statement with the help of following code snippet:

<html>

   <body>  

      Demonstrating If else If statement

   </br>

      <script type = "text/javascript">

            var website = "Tools QA";

            if(website == "google"){

               document.write("You are on goolge");

            }else if(website == "Tools QA"){

               document.write("You are on Tools QA");

            }else{

               document.write("Invalid Website");        

            }

            document.write("</br>");

      </script>      

   </body>

</html>

Save the file with name ifElseIfStatement.html and open it in any browser (Chrome, Firefox, or IE). It should show the output as

 If else if

As is evident from the above screenshot, as the value of variable website was "Tools QA", so the first if condition evaluates to false and moves the execution to next "if condition", where the condition evaluates to true and prints the value "You are on Tools QA".

How to write Switch Case in JavaScript?

The switch Case statement is an alternative for many if-else if statements that compare the same variable with a different set of values. A switch statement provides an easy way to execute different sets of statements based on the value of a variable. If the variable didn’t match any of the cases, then it will execute the default case statements. Its syntax looks like below:

Syntax:

switch(variable){
  case condition1:   //If condition matches the value of variable
  code statements;//Execute this code
  break; //come out of switch case  block

  case condition2:
  code statements;
  break;
  .
  .
  .

  case conditionN:
  code statements;
  break;

  default:
  code statements;

}

Note: If the break statement is not there, it will execute the subsequent condition as well, even if it does meet the first condition. Don't worry; we have an example of the same later in the chapter.

Let's understand the working of "switch-case" conditional statement with the help of following code snippet:

<html>

<body>

Demonstrating Switch statement

</br>

<script type="text/javascript">

    var operator = "+";

    var a = 5;

    var b = 7;

    var result;

    switch (operator) {

        case '+':
            result = a + b;
            document.write('Addtion: ' + result + '</br>');
            break;

            
        case '-':
            result = a - b;
            document.write('Subtraction: ' + result + '</br>');
            break;

            
        case '*':
            result = a * b;
            document.write('Multiplication: ' + result + '</br>');
            break;

            
        case '/':
            result = a / b;
            document.write('Division: ' + result + '</br>');
            break;

            
        default:
            result = "Invalid operation";
            document.write('Invalid: ' + result + '</br>');

    }

    document.write("</br>");

</script>

</body>

</html>

Save the file with name switchStatement.html and open it in any browser (Chrome, Firefox, or IE). It should show the output as: Switch with break Statement

As is evident from the above screenshot, the value of the variable "operator" was "+". So, it retuned the addition of the given numbers and skipped the other statements.

Note: Break statements play a significant role in switch-case statements.

Try the following code that uses switch-case statement without any break statements:

<html>

<body>

Demonstrating Switch statement

</br>

<script type="text/javascript">

    var operator = "+";

    var a = 5;

    var b = 7;

    var result;

    switch (operator) {

        case '+':
            result = a + b;
            document.write('Addtion: ' + result + '</br>');

            
        case '-':
            result = a - b;
            document.write('Subtraction: ' + result + '</br>');

            
        case '*':
            result = a * b;
            document.write('Multiplication: ' + result + '</br>');

            
        case '/':
            result = a / b;
            document.write('Division: ' + result + '</br>');

            
        default:
            result = "Invalid operation";
            document.write('Invalid: ' + result + '</br>');

    }

    document.write("</br>");

</script>

</body>

</html>

Save the file with name switchStatement.html and open it in any browser (Chrome, Firefox, or IE). It should show the output as:  Example of Switch Without Break

So, it clearly shows that, if break statements miss, it goes through all the case statements and executes all of them. So, usage of the break statement is a must for each of the case statements, so as the control flow exits just after executing the correct statement.

Key Takeaways

  • Conditional statements are program statements that help in deciding the flow control of the program based on a condition.
  • If you want to perform an action or execute some code only if some condition is true, use the "If" Statement.
  • In case you want that particular piece of code should execute only if the condition is true and should execute another piece of code if the condition is false, use the "If-else" Statement.
  • If you want to evaluate multiple conditions in the program flow, then you can use an advanced version of “If Else", called “If Else If ” conditional statement.
  • If you have the same variable which needs comparison against multiple values, you can use the "Switch-case" statement.

Let's now move to the next article to understand details of various kinds of  Loops supported by JavaScript.

JavaScript Operators
JavaScript Operators
Previous Article
JavaScript Loops
JavaScript Loops
Next Article
Arunkumar Chandra
Test USer
Reviewers
Ravinder Singh's Photo
Ravinder Singh

Similar Articles

Feedback