DeveloperBreeze

Section 2.3: Operators

Tutorial 2.3.2: Comparison and Logical Operators


Comparison and Logical Operators in JavaScript

Comparison and logical operators allow you to compare values and perform logical operations. They are fundamental for decision-making in JavaScript, such as in if statements and loops.


1. Comparison Operators

Comparison operators compare two values and return a boolean (true or false).

OperatorSymbolDescriptionExampleResult
Equal to==Checks if values are equal5 == '5'true
Strict Equal to===Checks if values and types are equal5 === '5'false
Not Equal to!=Checks if values are not equal5 != '5'false
Strict Not Equal to!==Checks if values and types are not equal5 !== '5'true
Greater than>Checks if left is greater than right10 > 5true
Greater than or Equal to>=Checks if left is greater than or equal to right10 >= 10true
Less than<Checks if left is less than right3 < 8true
Less than or Equal to<=Checks if left is less than or equal to right3 <= 3true

Examples of Comparison Operators

console.log(5 == "5"); // true (type coercion)
console.log(5 === "5"); // false (no type coercion)
console.log(10 > 7); // true
console.log(4 <= 4); // true

2. Logical Operators

Logical operators combine multiple conditions or values.

OperatorSymbolDescriptionExampleResult
AND&&Returns true if both conditions are truetrue && falsefalse
OR||Returns true if at least one condition is truetrue || falsetrue
NOT!Reverses the boolean value!truefalse

Examples of Logical Operators

// AND operator
console.log(true && true); // true
console.log(true && false); // false

// OR operator
console.log(false || true); // true
console.log(false || false); // false

// NOT operator
console.log(!true); // false
console.log(!false); // true

Combining Comparison and Logical Operators

Use comparison and logical operators together for complex conditions.

Example:

let age = 20;
let hasID = true;

if (age >= 18 && hasID) {
  console.log("Access granted.");
} else {
  console.log("Access denied.");
}
// Output: "Access granted."

Common Errors

  1. Confusing == with ===:
  • == performs type coercion.
  • === ensures both value and type match.
  1. Using && or || incorrectly:
  • Logical operators evaluate left to right; ensure your conditions are correct.

Exercise

  1. Check if a number is greater than 10 and even.
  2. Write a condition to determine if a user can log in based on the following:
  • The user must be logged in (isLoggedIn is true).
  • The user's account must not be suspended (isSuspended is false).

Example:

let number = 12;
if (number > 10 && number % 2 === 0) {
  console.log("The number is greater than 10 and even.");
}

let isLoggedIn = true;
let isSuspended = false;

if (isLoggedIn && !isSuspended) {
  console.log("User can log in.");
} else {
  console.log("Access denied.");
}

Continue Reading

Discover more amazing content handpicked just for you

Tutorial
javascript

Arithmetic Operators

  • Converts the operand to a number and negates it.
  • Example:
     let x = "5";
     let num = -x; // -5 (number)

Dec 11, 2024
Read More
Tutorial
javascript

Non-Primitive Data Types (Objects, Arrays, and Functions)

  • Iterating Over Arrays:
  for (let fruit of fruits) {
    console.log(fruit);
  }

Dec 11, 2024
Read More
Tutorial
javascript

Primitive Data Types

  let currentUser = null;
  console.log(currentUser); // null

Symbols are unique identifiers.

Dec 11, 2024
Read More
Tutorial
javascript

Variables and Constants

     const API_KEY = "12345";
     // API_KEY = "67890"; // Error: Assignment to constant variable
  • Variables are accessible only within the block they are declared in.
  • Example:

Dec 10, 2024
Read More
Tutorial
javascript

Hello World and Comments

Comments are notes in the code that are ignored by the JavaScript engine. They are useful for explaining what the code does or for temporarily disabling parts of the code.

  • Begin with //.
  • Example:

Dec 10, 2024
Read More
Tutorial
javascript css +1

How to Create a Chrome Extension for Automating Tweets on X (Twitter)

let intervalId = null;
const tweets = ["https://developerbreeze.com/post/59"];
let engage = [
  "Want to code like a pro? 🚀 These tutorials will get you there in no time! 💻🔥",
  "Struggling with coding? 🧠 These beginner-friendly tips will blow your mind! 🤯",
];

let currentTweetIndex = 0;

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === "start") {
    if (!intervalId) {
      intervalId = setInterval(() => {
        const currentTweet = tweets[currentTweetIndex];
        const randomEngage = engage[Math.floor(Math.random() * engage.length)];
        const tweet = `${randomEngage} ${currentTweet}`;

        const encodedTweet = encodeURIComponent(tweet);
        const shareUrl = `https://x.com/intent/tweet?text=${encodedTweet}`;

        chrome.tabs.create({ url: shareUrl, active: true }, (tab) => {
          chrome.tabs.onUpdated.addListener(function listener(tabId, info) {
            if (tabId === tab.id && info.status === "complete") {
              chrome.tabs.onUpdated.removeListener(listener);
              chrome.scripting.executeScript({
                target: { tabId },
                files: ["content.js"],
              });
            }
          });
        });

        currentTweetIndex = (currentTweetIndex + 1) % tweets.length;
      }, 300000); // Post every 5 minutes
      sendResponse({ status: "Running" });
    } else {
      sendResponse({ status: "Already Running" });
    }
  } else if (request.action === "stop") {
    clearInterval(intervalId);
    intervalId = null;
    sendResponse({ status: "Stopped" });
  }
});

The content.js file interacts directly with the X website to type and post tweets. Add the following code:

Dec 10, 2024
Read More
Tutorial
javascript

JavaScript Tutorial for Absolute Beginners

console.log("Hello, World!");
  • Open index.html in your web browser.
  • Right-click and select "Inspect" or press Ctrl + Shift + I to open the Developer Tools.
  • Go to the "Console" tab to see the message.

Sep 02, 2024
Read More
Tutorial
javascript

Creating a Dropdown Menu with JavaScript

Adding animations can make the dropdown menu more visually appealing. We can use CSS transitions to achieve a smooth fade-in and fade-out effect.

/* styles.css */
.dropdown-menu {
  display: none;
  position: absolute;
  background-color: #333;
  min-width: 160px;
  z-index: 1;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.dropdown-menu.show {
  display: block;
  opacity: 1;
}

Sep 02, 2024
Read More
Tutorial
javascript

Understanding JavaScript Classes

Example:

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  greet() {
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  }
}

const john = new Person('John', 30);
john.greet(); // Output: Hello, my name is John and I am 30 years old.

Sep 02, 2024
Read More
Tutorial
javascript

Asynchronous JavaScript: A Beginner's Guide

function fetchData(callback) {
    setTimeout(() => {
        callback("Data fetched");
    }, 2000);
}

console.log("Start");
fetchData((message) => {
    console.log(message);
});
console.log("End");
Start
End
Data fetched

Aug 30, 2024
Read More
Tutorial
javascript

Understanding the DOM in JavaScript: A Comprehensive Guide

   const element = document.getElementById('myElement');
   const elements = document.getElementsByClassName('myClass');

Aug 30, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!