Use Conditional Operator in JavaScript

HTMLHTMLBeginner
Practice Now

Introduction

In this lab, students will explore the usage of the conditional operator in JavaScript through a hands-on example. The lab guides learners through creating an HTML file, defining comparison variables, implementing conditional operator logic, and displaying results using document write.

Participants will start by setting up a basic HTML structure with an embedded script tag, then define variables such as age, student status, and country. They will learn how to use the conditional operator to perform concise conditional evaluations, understanding its syntax and practical application in making quick decision-based assignments within JavaScript code.

Create HTML File for Conditional Operator Example

In this step, you'll create an HTML file to demonstrate the usage of the conditional operator in JavaScript. HTML files provide an excellent environment for writing and testing JavaScript code.

Open the WebIDE and navigate to the ~/project directory. Create a new file named conditional-operator.html by right-clicking in the file explorer and selecting "New File".

Here's the basic HTML structure you'll use to explore the conditional operator:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Conditional Operator Example</title>
  </head>
  <body>
    <h1>JavaScript Conditional Operator Demo</h1>

    <script>
      // JavaScript code will be added here in subsequent steps
    </script>
  </body>
</html>

This HTML file provides a simple structure with a script tag where you'll write JavaScript code to demonstrate the conditional operator. The <script> tag allows you to embed JavaScript directly in the HTML document.

Example output when you open this file in a web browser:

JavaScript Conditional Operator Demo

Make sure to save the file in the ~/project directory. In the next steps, you'll add JavaScript code to explore the conditional operator's functionality.

Define Variables for Comparison

In this step, you'll learn how to define variables for comparison using the conditional operator. Open the conditional-operator.html file you created in the previous step and add the following JavaScript code inside the <script> tag:

<script>
  // Define variables for comparison
  let age = 20;
  let isStudent = true;
  let country = "USA";
</script>

Let's break down the variables:

  • age is a number representing a person's age
  • isStudent is a boolean value indicating student status
  • country is a string representing the person's country

These variables will be used to demonstrate how the conditional operator works for making comparisons and decisions. In the next steps, you'll use these variables to create conditional logic.

Example output of variable values:

age: 20
isStudent: true
country: "USA"

Make sure to save the file after adding these variables. The variables are now ready to be used with the conditional operator in the upcoming steps.

Implement Conditional Operator Logic

In this step, you'll learn how to use the conditional (ternary) operator to implement simple logic based on the variables you defined earlier. The conditional operator provides a concise way to write if-else statements in a single line.

Update the <script> section in your conditional-operator.html file with the following code:

<script>
  // Previously defined variables
  let age = 20;
  let isStudent = true;
  let country = "USA";

  // Conditional operator examples
  let canVote = age >= 18 ? "Eligible to vote" : "Not eligible to vote";

  let studentStatus = isStudent
    ? "Student discount applies"
    : "No student discount";

  let travelMessage =
    country === "USA" ? "Domestic travel" : "International travel";
</script>

Let's break down the conditional operator syntax:

  • condition ? value_if_true : value_if_false
  • The first example checks if the person is 18 or older
  • The second example checks student status
  • The third example checks the country for travel type

Example output of conditional operator results:

canVote: "Eligible to vote"
studentStatus: "Student discount applies"
travelMessage: "Domestic travel"

The conditional operator provides a compact way to make decisions and assign values based on conditions. It's a more concise alternative to traditional if-else statements.

Display Result Using Document Write

In this step, you'll learn how to display the results of your conditional operator logic using document.write(). This method allows you to output text directly to the HTML document.

Update the <script> section in your conditional-operator.html file with the following code:

<script>
  // Previously defined variables and conditional operators
  let age = 20;
  let isStudent = true;
  let country = "USA";

  let canVote = age >= 18 ? "Eligible to vote" : "Not eligible to vote";
  let studentStatus = isStudent
    ? "Student discount applies"
    : "No student discount";
  let travelMessage =
    country === "USA" ? "Domestic travel" : "International travel";

  // Display results using document.write()
  document.write("<h2>Conditional Operator Results</h2>");
  document.write("<p>Voting Status: " + canVote + "</p>");
  document.write("<p>Student Discount: " + studentStatus + "</p>");
  document.write("<p>Travel Type: " + travelMessage + "</p>");
</script>

When you open this HTML file in a web browser, you'll see the results displayed on the page. The document.write() method allows you to output HTML content directly.

Example output in the browser:

Conditional Operator Results
Voting Status: Eligible to vote
Student Discount: Student discount applies
Travel Type: Domestic travel

Note: While document.write() is simple to use, it's generally recommended to use more modern methods like innerHTML or textContent in real-world applications.

Understand Conditional Operator Syntax

In this step, you'll dive deeper into the syntax and usage of the conditional (ternary) operator in JavaScript. Update the <script> section in your conditional-operator.html file with the following comprehensive example:

<script>
  // Basic conditional operator syntax
  // condition ? expression_if_true : expression_if_false

  // Example 1: Simple comparison
  let age = 20;
  let canDrive = age >= 16 ? "Can drive" : "Cannot drive";

  // Example 2: Nested conditional operator
  let score = 75;
  let grade =
    score >= 90
      ? "A"
      : score >= 80
        ? "B"
        : score >= 70
          ? "C"
          : score >= 60
            ? "D"
            : "F";

  // Example 3: Conditional operator with function calls
  function isEven(num) {
    return num % 2 === 0;
  }
  let number = 10;
  let evenOddMessage = isEven(number) ? "Even number" : "Odd number";

  // Display results
  document.write("<h2>Conditional Operator Syntax Examples</h2>");
  document.write("<p>Driving Eligibility: " + canDrive + "</p>");
  document.write("<p>Grade: " + grade + "</p>");
  document.write("<p>Number Type: " + evenOddMessage + "</p>");
</script>

Key points about the conditional operator syntax:

  • Basic format: condition ? value_if_true : value_if_false
  • Can be nested for multiple conditions
  • Can include function calls or complex expressions
  • Provides a compact alternative to if-else statements

Example output in the browser:

Conditional Operator Syntax Examples
Driving Eligibility: Can drive
Grade: C
Number Type: Even number

Summary

In this lab, participants learn how to use the conditional operator in JavaScript by creating an HTML file and implementing practical comparison logic. The lab guides learners through setting up a basic HTML structure with an embedded script tag, defining variables for comparison, and exploring the syntax of the conditional operator.

The step-by-step approach allows students to understand how to create dynamic comparisons using variables like age, student status, and country. By demonstrating the conditional operator's functionality within a web development context, the lab provides a hands-on method for understanding this essential JavaScript programming technique, enabling learners to write more concise and efficient conditional statements.