JavaScript and TypeScript course ยท Module 1: JavaScript Basics

Comparison and Logical Operators

8 min read ยท
In this lesson6

In Jurassic Park, the security system continuously makes decisions: does the electric fence have enough power? Is the security level adequate for this dinosaur species? Do weather conditions allow opening an attraction?

JavaScript, much like the park's security system, uses comparison and logical operators to make decisions in code.

Comparison Operators

Comparison operators allow you to compare values and return a boolean value (true or false). Working in Jurassic Park, the control system must constantly perform similar comparisons:

// Equality operator (==)
let threatLevel = 3;
let maxSafeLevel = 3;
console.log(threatLevel == maxSafeLevel); // true - levels are equal

// Strict equality operator (===)
let dinosaurCount = "5";
let expectedCount = 5;
console.log(dinosaurCount == expectedCount); // true - values are equal, but types differ
console.log(dinosaurCount === expectedCount); // false - different types (string vs number)

// Inequality operator (!=)
let availableResources = 500;
let requiredResources = 600;
console.log(availableResources != requiredResources); // true - values are different

// Strict inequality operator (!==)
let fenceStatus = "active";
let requiredStatus = "active";
console.log(fenceStatus !== requiredStatus); // false - they are identical (same strings)

// Greater than operator (>)
let troposphericTemperature = 38; // in degrees Celsius
let safeTemperature = 35;
console.log(troposphericTemperature > safeTemperature); // true - temperature is higher

// Less than operator (<)
let waterLevel = 80; // percent of capacity
let criticalLevel = 20;
console.log(waterLevel < criticalLevel); // false - water level is not below critical

// Greater than or equal operator (>=)
let employeeCount = 45;
let minimumStaff = 45;
console.log(employeeCount >= minimumStaff); // true - exactly the minimum required number

// Less than or equal operator (<=)
let systemLoad = 75; // percent
let maxLoad = 80;
console.log(systemLoad <= maxLoad); // true - load is below maximum

Difference Between == and ===

In Jurassic Park, precision is key. Similarly in JavaScript, there is an important difference between equality operators:

  • == (equality) - compares only values, performing type conversion if necessary
  • === (strict equality) - compares both values and data types
// Jurassic Park examples:

// Scenario 1: Conversion from database (string) to numeric value
let reportedRaptorCount = "6";  // data from system as a string
let actualRaptorCount = 6;      // numeric value

// Comparison with type conversion
if (reportedRaptorCount == actualRaptorCount) {
  console.log("Raptor counts match"); // this will execute
}

// Comparison without type conversion
if (reportedRaptorCount === actualRaptorCount) {
  console.log("This message won't be displayed");
} else {
  console.log("Data type discrepancy detected!"); // this will execute
}

// Scenario 2: Comparing unknown values (null and undefined)
let unknownStatus = null;
let undefinedStatus;  // will automatically be undefined

console.log(unknownStatus == undefinedStatus);  // true (== treats null and undefined as equal)
console.log(unknownStatus === undefinedStatus); // false (=== distinguishes null from undefined)

Comparing Objects

Just as two Velociraptors may look similar but be different individuals, objects in JavaScript are compared by reference, not by value:

// Two dinosaurs with the same traits, but they are different individuals
let raptor1 = { species: "Velociraptor", age: 3, aggression: "high" };
let raptor2 = { species: "Velociraptor", age: 3, aggression: "high" };

console.log(raptor1 == raptor2);  // false - different objects in memory
console.log(raptor1 === raptor2); // false - different objects in memory

// Assigning the same reference
let raptorReference = raptor1;
console.log(raptor1 === raptorReference); // true - same reference in memory

Logical Operators

In Jurassic Park, decisions are rarely simple. Should we open an attraction? That depends on weather, staff availability, security status, and other factors. Logical operators allow combining conditions:

// AND operator (&&) - returns true only when both conditions are true
let fenceWorking = true;
let dinoTrackingSystem = true;
let securityEnsured = fenceWorking && dinoTrackingSystem;
console.log(securityEnsured); // true - both systems are working

// OR operator (||) - returns true when at least one condition is true
let mainPower = false;
let backupPower = true;
let parkHasPower = mainPower || backupPower;
console.log(parkHasPower); // true - at least one power source is working

// NOT operator (!) - reverses the boolean value
let parkClosed = false;
let parkOpen = !parkClosed;
console.log(parkOpen); // true - the opposite of closed is open

Complex Logical Conditions

In reality, Jurassic Park systems must consider many factors simultaneously:

// Can we open the Tyrannosaurus exhibit?
let weatherSuitable = true;
let staffPresent = true;
let powerStable = true;
let sufficientFoodSupply = false;
let allDinosaursHealthy = true;

// Opening condition: all factors must be positive
let canOpenExhibit = weatherSuitable && staffPresent && powerStable &&
                     sufficientFoodSupply && allDinosaursHealthy;
console.log(canOpenExhibit); // false - insufficient food supply

// Alarm condition: bad weather OR no power
let alarmCondition = !weatherSuitable || !powerStable;
console.log(alarmCondition); // false - no reason for alarm

// Complex condition: if staff present AND (power OR backup generators)
let backupGeneratorsWorking = true;
let operationalConditions = staffPresent && (powerStable || backupGeneratorsWorking);
console.log(operationalConditions); // true - basic conditions are met

Short-Circuit Evaluation

The && and || operators use the "short-circuit" technique, meaning the second condition may not even be evaluated:

// Example with && (AND):
let securitySystem = false;

function checkDinosaurStatus() {
  console.log("Checking dinosaur locations...");
  return true;
}

// When the first condition is false, the second is not checked
let parkSafe = securitySystem && checkDinosaurStatus();
// Nothing will appear in the console: the function is not called

// Example with || (OR):
let mainPowerSupply = true;

function startGenerators() {
  console.log("Starting generators...");
  return true;
}

// When the first condition is true, the second is not checked
let operationalPower = mainPowerSupply || startGenerators();
// Nothing will appear in the console: the function is not called

Truthy and Falsy Values

In JavaScript, not only boolean values (true and false) are used in conditions. Every value has its "truthiness":

Falsy values:

  • false
  • 0
  • "" (empty string)
  • null
  • undefined
  • NaN

All other values are truthy.

// Jurassic Park examples:

// Checking if a dinosaur has an assigned name
let dinosaurName = ""; // No name (empty string)
if (dinosaurName) {
  console.log("Dinosaur has a name: " + dinosaurName);
} else {
  console.log("Dinosaur has no assigned name"); // This will execute
}

// Checking if a dinosaur identifier exists
let dinosaurId = 0; // ID 0 (falsy value)
if (dinosaurId) {
  console.log("Found dinosaur with ID: " + dinosaurId);
} else {
  console.log("No valid dinosaur ID found"); // This will execute
}

// Checking threat status (null means unknown)
let threatStatus = null;
if (threatStatus) {
  console.log("Threat level: " + threatStatus);
} else {
  console.log("Threat status unknown"); // This will execute
}

Conditional (Ternary) Operator

The conditional operator ? : works like a compact if...else and is often used for conditional assignments:

// Standard if...else construct
let enclosureStatus;
let raptorCount = 5;

if (raptorCount > 0) {
  enclosureStatus = "Occupied";
} else {
  enclosureStatus = "Empty";
}

// Same thing with the conditional operator
let enclosureStatus2 = raptorCount > 0 ? "Occupied" : "Empty";

console.log(enclosureStatus);  // "Occupied"
console.log(enclosureStatus2); // "Occupied"

// More complex example - assigning security level
let dinosaurSpecies = "Tyrannosaurus";
let securityLevel = dinosaurSpecies === "Tyrannosaurus" || dinosaurSpecies === "Spinosaurus" ?
                    "Maximum" :
                    dinosaurSpecies === "Velociraptor" ?
                    "High" :
                    "Standard";

console.log(`For species ${dinosaurSpecies}, required security level: ${securityLevel}`);
// "For species Tyrannosaurus, required security level: Maximum"

Optional Chaining Operator

In newer versions of JavaScript, the optional chaining operator ?. is available, which safely checks whether an object property exists before attempting to access it:

// Dinosaur data structure
let tyrannosaurus = {
  name: "Rex",
  stats: {
    age: 8,
    weight: 8000,
    diet: "carnivore"
  }
};

let triceratops = {
  name: "Tricy",
  // no stats
};

// Safely reading nested properties
console.log(tyrannosaurus.stats?.weight); // 8000
console.log(triceratops.stats?.weight); // undefined, no error

// Without optional chaining we would get an error:
// console.log(triceratops.stats.weight); // Error: Cannot read property 'weight' of undefined

Nullish Coalescing Operator

The ?? operator returns the right operand when the left is null or undefined, otherwise returns the left operand:

// Setting default values for missing data
let securityReport = {
  threat: 0,
  // no power status
};

// Using ?? to provide a default value when the property is null or undefined
let threatLevel = securityReport.threat ?? "Unknown";
let powerStatus = securityReport.power ?? "Undefined";

console.log(threatLevel); // 0 (value 0 is not null or undefined, so it's returned)
console.log(powerStatus); // "Undefined" (property doesn't exist, so the default is used)

// Comparison with || (OR)
let threatLevelOr = securityReport.threat || "Unknown";
console.log(threatLevelOr); // "Unknown" (0 is falsy, so the default is returned)

Summary

Comparison and logical operators in JavaScript, much like the decision-making systems in Jurassic Park, allow you to:

  • Compare values and types (==, ===, !=, !==, >, <, >=, <=)
  • Combine conditions (&&, ||, !)
  • Create compact conditional expressions (? :)
  • Safely access object properties (?.)
  • Provide default values for null/undefined (??)

With these operators, we can create intelligent decision-making systems that react to various conditions - just as Jurassic Park's security systems must react to changing circumstances to maintain control over a park full of dangerous dinosaurs.

In the next lesson, we will look at operator precedence, that is, the order in which JavaScript evaluates operations in complex expressions.

Code for this lesson: index.js
// Comparison and logical operators
// Jurassic Park security system

// === Comparison operators ===
console.log("=== Comparison operators ===");

let voltage = 10000;
let minimum = 8000;

console.log("voltage > minimum:", voltage > minimum);     // true
console.log("voltage < minimum:", voltage < minimum);     // false
console.log("voltage >= 10000:", voltage >= 10000);       // true
console.log("voltage <= 5000:", voltage <= 5000);         // false

// == vs === (equality vs strict equality)
console.log("\n=== == vs === ===");
console.log("5 == '5':", 5 == '5');     // true (compares values)
console.log("5 === '5':", 5 === '5');   // false (compares values AND types)
console.log("null == undefined:", null == undefined);   // true
console.log("null === undefined:", null === undefined); // false

// != vs !==
console.log("5 != '5':", 5 != '5');     // false
console.log("5 !== '5':", 5 !== '5');   // true

// === Logical operators ===
console.log("\n=== Logical operators ===");

let fenceActive = true;
let personnelSafe = true;
let stormComing = false;

// AND (&&) - both conditions must be true
console.log("Can open the park:", fenceActive && personnelSafe);

// OR (||) - one condition is enough true
console.log("Needs attention:", !fenceActive || stormComing);

// NOT (!) - negation
console.log("Fence inactive:", !fenceActive);

// Combining operators
let canOpen = fenceActive && personnelSafe && !stormComing;
console.log("\nOpening decision:", canOpen);

// Your task:
// 1. Check the difference between == and ===
// 2. Combine several conditions with && and || operators

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What will the comparison 5 === '5' return in JavaScript?

  2. 2. When does the logical operator && (AND) return true?

Hands-on tasks in the game

  • Click in order

    Arrange an expression that checks whether dinoCount is strictly equal to expectedCount (variables in this order):

  1. QuestionDifference Between == and ===
  2. QuestionLogical Operator &&
  3. Click in orderStrict Comparison Syntax

Useful articles