Conditional Statements

Conditional statements are the backbone of logic in programming. In this section, we'll explore how to use these constructs in JavaScript to control the flow of a program. Understanding these concepts is crucial for making decisions in code and for executing repetitive tasks efficiently.

Desired Outcomes:

  • Learn how to use if, else if, else, and switch statements to execute different code branches based on different conditions.
  • Understand how to use logical operators (&&, ||, !) in conditional statements for complex condition checking.
  • Master the use of the ternary (condition ? expr1 : expr2) as a shorthand for if-else statements.

When writing programs, there are often situations where it is necessary to choose one of several predetermined ways of execution. In such cases, it is necessary to use conditional statements that allow the program to make accurate decisions depending on a certain condition. 

JavaScript supports conditional statements that are used to perform different actions based on different conditions.

If Statement

JavaScript supports the following forms of the if statement:

  • if – executes the code within the if statement if the condition is true 
  • if...else – executes the code within the if statement if the condition is true, and if it is not, executes the code within the else statement
  • if...else if - executes the code within the if statement if the condition is true, if another condition is true, it executes the code within the else if statement

The if statement executes certain code if the specified condition is true.

if (condition) {
    // code
}

Inside the if statement, the given condition is evaluated. If the condition is met, i.e., returns true, the code within the curly braces will be executed, if it returns false, nothing will be executed. When writing conditional statements, you will most often use comparison operators explained in previous lessons of the manual.

In the example below, a simple if statement is written that checks if the variable years is greater than 18, if it is, it writes in the HTML document "You are of age!".

<html>
   <body>
      <script type="text/javascript">
        var age = 20;

        if(age >= 18){
           document.write("<b>You are of age!</b>");
        }
     </script>
   </body>
</html>

Try to print the given example in the HTML document and change the value for the years variable and see what happens with the code execution.

The if...else statement is the next form of a conditional statement that allows JavaScript to execute code with greater control.

if(condition) {
    // Code to be executed if the if statement returns true
} else {
    // Code to be executed if the if statement returns false
}

Here the JavaScript condition is evaluated again, but in the if...else form, if the if block returns false, i.e., the condition is not met, the code in the else block will be executed.

<html>
   <body>
      <script type="text/javascript">
         var age = 20;

         if(age >= 18){
            document.write("<b>You are of age!</b>");
         } else {
            document.write("<b>You are underage!</b>");
         }
      </script>
   </body>
</html>

In the example, the else statement is added which writes "You are underage!", if the value of the years variable is less than 18.

The next form of the if statement is if...else if, which can be given more conditions. The mentioned command allows JavaScript to make an accurate decision based on multiple conditions. The syntax of the if..else if statement is as follows.

if(firstCondition) {
    // Code to be executed if the if statement returns true
} else if (secondCondition) {
    // Code to be executed if the else if statement returns true
} else if (thirdCondition) {
    // Code to be executed if the else if statement returns true
} else {
    // Code to be executed if the if and else if statements return false
}

The above code is just a series of if statements. The code will be executed depending on which condition first returns true. If all conditions return false, the code under the else command will be executed.

<html>
   <body>
      <script type="text/javascript">
         var age = 20;

         if(age >= 18){
            document.write("<b>You are of age!</b>");
         } else if (age < 18) {
            document.write("<b>You are underage!</b>");
         } else {
            document.write("<b>You did not enter a numerical value!</b>");
         }
      </script>
   </body>
</html>

Switch Statement

The task of the switch statement is the same as the if statement, but it is more suitable for complex evaluations. The switch command is passed a certain expression, and cases are entered for evaluation. The interpreter component checks each case until the case meets the condition, i.e., returns true. If none of the cases meet the condition, the commands under the default case are executed.

The syntax of the switch command is as follows:

switch (expression)
{
    case state1:
      // code
    break;
    case state2:
      // code
    break;
    case stateN:
      // code
    break;
    default:
      //code
}

In the example below, the JavaScript interpreter component goes through the switch command from the first mentioned case to the last. When it comes to a case that returns true, which is in the example above case '3', the switch command breaks, and the code under the met case is executed.

<script type="text/javascript">
   var grade = '3';
   document.write("<h1>Printing grades using the switch command.</h1>");

   switch (grade)
   {
     case '5':
      document.write("Grade Excellent. <br />");
      break;
     case '4':
      document.write("Grade Very Good. <br />");
      break;
     case '3':
      document.write("Grade Good. <br />");
      break;
     case '2':
      document.write("Grade Satisfactory. <br />");
      break;
     case '1':
      document.write("Grade Insufficient. <br />");
      break;
     default:  
      document.write("Non-existing grade. <br />")
   }
</script>

If you were to remove the break; commands after each case. The interpreter would print the case '3', case '2', case '1', and default cases.

The Ternary Operator in JavaScript

The ternary operator in JavaScript is a concise way to execute conditional (if-else) statements. It is often used for assigning a value to a variable based on a condition. The syntax of the ternary operator is more succinct compared to traditional if-else statements, making your code more readable and compact, especially for simple conditions.

The basic syntax of the ternary operator is:

condition ? expressionIfTrue : expressionIfFalse;

Concepts:

  • Condition: An expression that is evaluated for a truthy or falsy value.
  • expressionIfTrue: The expression that is executed if the condition is truthy.
  • expressionIfFalse: The expression that is executed if the condition is falsy.

Basic Usage: 

Assigning a value to a variable based on a simple condition.

let age = 20;
let isAdult = (age >= 18) ? "Yes" : "No";
console.log(isAdult); // Output: "Yes"

Nested Ternary Operator:

You can nest ternary operators to handle multiple conditions.

let score = 85;
let grade = (score >= 90) ? 'A' :
 (score >= 80) ? 'B' :
 (score >= 70) ? 'C' :
 (score >= 60) ? 'D' : 'F';
console.log(grade); // Output: "B"

Replacing if-else Statement:

Ternary operators are useful for replacing simple if-else statements.

// Traditional if-else
let speed = 75;
let message;

if (speed > 60) {
 message = "Too fast";
} else {
 message = "Within limit";
}

// Using ternary operator
let message = (speed > 60) ? "Too fast" : "Within limit";
console.log(message); // Output: "Too fast"

Points to Remember:

  • The ternary operator is best suited for simple conditional statements. Overusing it, especially with nesting, can reduce code readability.
  • It is a great tool for inline operations and quick decision-making in your code.
  • Always prioritize code readability, especially when deciding whether to use a ternary operator or a traditional if-else statement.

This lesson should give you a solid understanding of how to effectively utilize the ternary operator in JavaScript, allowing for more concise and readable conditional statements in your programming endeavors.

Updated on:

Part of our complete: JavaScript Fundamentals guide

Want exercises and real projects for this lesson? Get the full course.