Javascript If-Else Statement

Sometimes you need to choose one of several pathways while writing your program. In such circumstances, conditional statements must be used to allow your software to make accurate judgments and conduct correct actions.

Conditional statements in JavaScript are used to execute various actions based on different criteria.

Suppose a particular condition is true; the "if statement" performs a statement. The optional "else" clause will execute another sentence if the condition is false.

This article will let you better understand how to utilize the if else statement in JS to execute a block depending on a condition.

Conditional Statements in Javascript

Here are the conditional statements available in JavaScript:

1. If - This will tell you if a code block should be executed. That's if the condition is true.

2. else - This will tell you if a code block should be executed. That's if the condition is false.

3. else if - This will specify the condition to be tested if the first (1st) condition turns out to be false

4. "Switch" will specify alternative blocks of code that should be executed.

1. Javascript's If Statement

The basic control statement which allows JavaScript to take decisions and carry out statements conditionally is the "if statement."

Syntax of If-Else Statement

if (condition) {
  //  code to be run if the condition turns out to be true
}

A JS expression is examined here. The specified statement(s) will be executed if the resultant value is true. If the expression is incorrect, no statement will be performed. When making decisions, you will almost always employ comparison operators.

Example of If-Else Statement

<html>
   <body>     
      <script type = "text/javascript">
         <!--
            var age = 15;
         
            if( age > 8 ) {
               document.write("<b>Qualifies for swimming</b>");
            }
         //-->
      </script>      
      <p>Set the variable to a different value and then try it out yourself...</p>
   </body>
</html>

2. Javascript's else Statement

The else statement will tell you if a block of code should be executed. That's if the condition is false.

if (condition) {
  //  code to be run if the condition turns out to be true
} else {
  //  code to be run if the condition turns out to be false
}

Example of If-Else Statement

If the grade is less than 50, create a "Fail" remark otherwise, create a "Pass" remark:

if (grade < 50) {
  remark = "Fail";
} else {
  remark = "Pass";
}

The result of this remark will be "Fail."

3. Javascript's else if Statement

The else if statement will specify the condition to be tested if the first (1st) condition turns out to be false.

This flowchart shows how the else if statement works:

JavaScript if else

Syntax

if( condition ) {
  // ...
} else { 
  // ...
}

Example of else if Statement

<html>
   <body>   
      <script type = "text/javascript">
         <!--
            var book = "english";
            if( book == "maths" ) {
               document.write("<b>Maths Book</b>");
            } else if( book == "english" ) {
               document.write("<b>English Book</b>");
            } else if( book == "chemistry" ) {
               document.write("<b>Chemistry Book</b>");
            } else {
               document.write("<b>Unknown Book</b>");
            }
         //-->
      </script>      
      <p>Set the variable to a different value and then try it out...</p>
   </body>
<html>

4. Javascript's Switch Statement

The JS switch statement enables you to execute a single piece of code from a collection of expressions. It is the same as the else if statement which we explained above. However, it is handier than if else since it may be used with integers, characters, and so on. To run one of the multiple code blocks, use the switch statement.

Syntax

switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}

Here's how it works:
Just once, the switch expression is evaluated.
The expression's value is compared to the values of each case.
If a match is found, the relevant piece of code is run.
If there's no discovered match, the default block of code will run.

Javascript Switch Statement Flowchart

Example of a very simple JS Switch Statement

<script>  
var grade='B';  
var result;  
switch(grade){  
case 'A':  
result="A Grade";  
break;  
case 'B':  
result="B Grade";  
break;  
case 'C':  
result="C Grade";  
break;  
default:  
result="No Grade";  
}  
document.write(result);  
</script>  

Break Keyword

When JavaScript encounters a break keyword, it will exit the switch block. The Break keyword will halt running the code in the switch block.  Breaking the last case in the switch block is not necessary. In any case, the block breaks (terminates) there.

Default Keyword

If there aren't any case matches, the default keyword will show the code to run:

The weekday comes back as a number between zero and six by the getDay() function.  If today is not a Friday (6) or a Saturday (0), type the following message:

switch (new Date().getDay()) {
  case 6:
    text = "Today is Friday";
    break;
  case 0:
    text = "Today is Saturday";
    break;
  default:
    text = "Excited for the Weekend";
}

Creating a Simple Calculator with JS Switch Statement

// Creating a Simple Calculator with JS Switch Statement
let result;

// take the operator input
const operator = prompt('Enter operator ( either +, -, * or / ): ');

// take the operand input
const number1 = parseFloat(prompt('Enter first number: '));
const number2 = parseFloat(prompt('Enter second number: '));

switch(operator) {
    case '+':
        result = number1 + number2;
        console.log(`${number1} + ${number2} = ${result}`);
        break;
    case '-':
        result = number1 - number2;
        console.log(`${number1} - ${number2} = ${result}`);
        break;
    case '*':
        result = number1 * number2;
        console.log(`${number1} * ${number2} = ${result}`);
        break;
    case '/':
        result = number1 / number2;
        console.log(`${number1} / ${number2} = ${result}`);
        break;

    default:
        console.log('Invalid operator');
        break;
}