Explore Logical Operators in JavaScript

JavaScriptJavaScriptBeginner
Practice Now

Introduction

In this lab, participants will explore the fundamental logical operators in JavaScript through a hands-on web development exercise. The lab guides learners through creating an HTML file and implementing practical demonstrations of AND (&&), OR (||), and NOT (!) logical operators, providing a comprehensive understanding of how these operators work in JavaScript programming.

By following a step-by-step approach, students will set up an interactive web page that displays the results of various logical operations, enabling them to understand how these operators evaluate conditions and return boolean values. The lab emphasizes practical learning by using real-world scenarios like driving eligibility and user authentication to illustrate the application of logical operators in JavaScript.

Set Up HTML File for Logical Operators Demonstration

In this step, you'll create a basic HTML file that will serve as the foundation for demonstrating JavaScript logical operators. We'll set up a simple web page structure with a script section where we'll explore logical operations.

Open the WebIDE and navigate to the ~/project directory. Create a new file called logical-operators.html using the WebIDE interface.

Here's the initial HTML structure you'll use:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>JavaScript Logical Operators Demo</title>
  </head>
  <body>
    <h1>Exploring Logical Operators in JavaScript</h1>

    <div id="output"></div>

    <script>
      // We'll add our JavaScript logical operator examples here
    </script>
  </body>
</html>

Let's break down the key components of this HTML file:

  • The <!DOCTYPE html> declaration specifies this is an HTML5 document
  • We've added a title and a heading to describe the page
  • The <div id="output"> will be used to display our logical operator results
  • The <script> tag is where we'll write our JavaScript code

Example output when you open this file in a browser:

Exploring Logical Operators in JavaScript

Implement AND (&&) Logical Operation

In this step, you'll learn about the AND (&&) logical operator in JavaScript. The AND operator returns true only when both operands are true, otherwise it returns false.

Open the logical-operators.html file you created in the previous step. Inside the <script> tag, add the following JavaScript code to demonstrate the AND operator:

// AND (&&) Logical Operator Demonstration
function demonstrateAndOperator() {
  let output = document.getElementById("output");

  // Example 1: Simple boolean AND
  let isAdult = true;
  let hasLicense = true;
  let canDrive = isAdult && hasLicense;
  output.innerHTML += `Can drive? ${canDrive}<br>`;

  // Example 2: Comparison AND
  let age = 25;
  let hasValidLicense = age >= 18 && age <= 65;
  output.innerHTML += `Valid driving age? ${hasValidLicense}<br>`;

  // Example 3: Multiple conditions
  let isMember = true;
  let hasDiscount = true;
  let canGetSpecialOffer = isMember && hasDiscount;
  output.innerHTML += `Special offer available? ${canGetSpecialOffer}<br>`;
}

// Call the function when the page loads
demonstrateAndOperator();

Let's break down the AND (&&) operator:

  • It returns true only if both conditions are true
  • In the first example, canDrive is true only if both isAdult and hasLicense are true
  • The second example uses comparison operators with AND
  • The third example shows how AND can combine multiple boolean conditions

Example output in the browser:

Can drive? true
Valid driving age? true
Special offer available? true

Implement OR (||) Logical Operation

In this step, you'll learn about the OR (||) logical operator in JavaScript. The OR operator returns true if at least one of the operands is true, otherwise it returns false.

Open the logical-operators.html file and add a new function to demonstrate the OR operator inside the <script> tag:

// OR (||) Logical Operator Demonstration
function demonstrateOrOperator() {
  let output = document.getElementById("output");

  // Example 1: Simple boolean OR
  let isWeekend = false;
  let isHoliday = true;
  let canRelax = isWeekend || isHoliday;
  output.innerHTML += `Can relax? ${canRelax}<br>`;

  // Example 2: Comparison OR
  let age = 16;
  let hasParentalConsent = true;
  let canAttendEvent = age >= 18 || hasParentalConsent;
  output.innerHTML += `Can attend event? ${canAttendEvent}<br>`;

  // Example 3: Multiple conditions
  let hasCoupon = false;
  let isNewCustomer = true;
  let canGetDiscount = hasCoupon || isNewCustomer;
  output.innerHTML += `Eligible for discount? ${canGetDiscount}<br>`;
}

// Call the function when the page loads
demonstrateOrOperator();

Let's break down the OR (||) operator:

  • It returns true if at least one condition is true
  • In the first example, canRelax is true because isHoliday is true
  • The second example shows how OR can be used with comparison and boolean conditions
  • The third example demonstrates combining multiple conditions

Example output in the browser:

Can relax? true
Can attend event? true
Eligible for discount? true

Implement NOT (!) Logical Operation

In this step, you'll learn about the NOT (!) logical operator in JavaScript. The NOT operator inverts the boolean value of an expression, turning true to false and false to true.

Open the logical-operators.html file and add a new function to demonstrate the NOT operator inside the <script> tag:

// NOT (!) Logical Operator Demonstration
function demonstrateNotOperator() {
  let output = document.getElementById("output");

  // Example 1: Basic NOT operation
  let isRaining = false;
  let isSunny = !isRaining;
  output.innerHTML += `Is it sunny? ${isSunny}<br>`;

  // Example 2: NOT with comparison
  let age = 16;
  let isAdult = !(age < 18);
  output.innerHTML += `Is an adult? ${isAdult}<br>`;

  // Example 3: Negating a complex condition
  let hasTicket = true;
  let isCrowded = true;
  let canEnter = !(hasTicket && isCrowded);
  output.innerHTML += `Can enter? ${canEnter}<br>`;
}

// Call the function when the page loads
demonstrateNotOperator();

Let's break down the NOT (!) operator:

  • It reverses the boolean value of an expression
  • In the first example, isSunny becomes true because isRaining is false
  • The second example shows NOT used with a comparison
  • The third example demonstrates NOT with a more complex condition

Example output in the browser:

Is it sunny? true
Is an adult? false
Can enter? false

Display Logical Operation Results on Web Page

In this step, you'll combine all the logical operators you've learned and create a comprehensive demonstration that displays the results on the web page. We'll modify the HTML file to include a more structured approach to showing logical operator results.

Update the logical-operators.html file with the following complete code:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>JavaScript Logical Operators Demo</title>
    <style>
      body {
        font-family: Arial, sans-serif;
        max-width: 600px;
        margin: 0 auto;
        padding: 20px;
      }
      .result {
        margin: 10px 0;
        padding: 10px;
        background-color: #f0f0f0;
      }
    </style>
  </head>
  <body>
    <h1>JavaScript Logical Operators Exploration</h1>

    <div id="andResults" class="result">
      <h2>AND (&&) Operator Results</h2>
    </div>

    <div id="orResults" class="result">
      <h2>OR (||) Operator Results</h2>
    </div>

    <div id="notResults" class="result">
      <h2>NOT (!) Operator Results</h2>
    </div>

    <script>
      // Function to display results
      function displayResult(elementId, message) {
        const element = document.getElementById(elementId);
        const resultLine = document.createElement("p");
        resultLine.textContent = message;
        element.appendChild(resultLine);
      }

      // AND (&&) Operator Demonstration
      function demonstrateAndOperator() {
        let isAdult = true;
        let hasLicense = true;
        let canDrive = isAdult && hasLicense;
        displayResult("andResults", `Can drive? ${canDrive}`);

        let age = 25;
        let hasValidLicense = age >= 18 && age <= 65;
        displayResult("andResults", `Valid driving age? ${hasValidLicense}`);
      }

      // OR (||) Operator Demonstration
      function demonstrateOrOperator() {
        let isWeekend = false;
        let isHoliday = true;
        let canRelax = isWeekend || isHoliday;
        displayResult("orResults", `Can relax? ${canRelax}`);

        let age = 16;
        let hasParentalConsent = true;
        let canAttendEvent = age >= 18 || hasParentalConsent;
        displayResult("orResults", `Can attend event? ${canAttendEvent}`);
      }

      // NOT (!) Operator Demonstration
      function demonstrateNotOperator() {
        let isRaining = false;
        let isSunny = !isRaining;
        displayResult("notResults", `Is it sunny? ${isSunny}`);

        let age = 16;
        let isAdult = !(age < 18);
        displayResult("notResults", `Is an adult? ${isAdult}`);
      }

      // Run all demonstrations when page loads
      function runAllDemonstrations() {
        demonstrateAndOperator();
        demonstrateOrOperator();
        demonstrateNotOperator();
      }

      // Call the main function when the page loads
      window.onload = runAllDemonstrations;
    </script>
  </body>
</html>

Key improvements in this version:

  • Added styled result sections for each logical operator
  • Created a displayResult() function to show results
  • Implemented a runAllDemonstrations() function to execute all operator demonstrations
  • Added basic CSS to improve readability
  • Used window.onload to ensure all scripts run after the page loads

Example browser output will show results for AND, OR, and NOT operators in separate, styled sections.

Summary

In this lab, participants explored JavaScript logical operators through a hands-on web development exercise. The lab began by creating an HTML file with a dedicated output div, setting up a structured environment for demonstrating logical operations. Participants learned about the AND (&&), OR (||), and NOT (!) operators, implementing practical examples that showcase how these logical operators evaluate boolean expressions and control program flow.

The interactive approach allowed learners to understand each logical operator's behavior by writing JavaScript code directly within the HTML file. By manipulating boolean values and using comparison techniques, participants gained insights into how logical operators can be used to make conditional decisions and create more complex logical evaluations in JavaScript programming.

Other JavaScript Tutorials you may like