We use cookies to enhance your experience on the site
CodeWorlds

Comparison and Logical Operators

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:

1// Equality operator (==)
2let threatLevel = 3;
3let maxSafeLevel = 3;
4console.log(threatLevel == maxSafeLevel); // true - levels are equal
5
6// Strict equality operator (===)
7let dinosaurCount = "5";
8let expectedCount = 5;
9console.log(dinosaurCount == expectedCount); // true - values are equal, but types differ
10console.log(dinosaurCount === expectedCount); // false - different types (string vs number)
11
12// Inequality operator (!=)
13let availableResources = 500;
14let requiredResources = 600;
15console.log(availableResources != requiredResources); // true - values are different
16
17// Strict inequality operator (!==)
18let fenceStatus = "active";
19let requiredStatus = "active";
20console.log(fenceStatus !== requiredStatus); // false - they are identical (same strings)
21
22// Greater than operator (>)
23let troposphericTemperature = 38; // in degrees Celsius
24let safeTemperature = 35;
25console.log(troposphericTemperature > safeTemperature); // true - temperature is higher
26
27// Less than operator (<)
28let waterLevel = 80; // percent of capacity
29let criticalLevel = 20;
30console.log(waterLevel < criticalLevel); // false - water level is not below critical
31
32// Greater than or equal operator (>=)
33let employeeCount = 45;
34let minimumStaff = 45;
35console.log(employeeCount >= minimumStaff); // true - exactly the minimum required number
36
37// Less than or equal operator (<=)
38let systemLoad = 75; // percent
39let maxLoad = 80;
40console.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
1// Jurassic Park examples:
2
3// Scenario 1: Conversion from database (string) to numeric value
4let reportedRaptorCount = "6";  // data from system as a string
5let actualRaptorCount = 6;      // numeric value
6
7// Comparison with type conversion
8if (reportedRaptorCount == actualRaptorCount) {
9  console.log("Raptor counts match"); // this will execute
10}
11
12// Comparison without type conversion
13if (reportedRaptorCount === actualRaptorCount) {
14  console.log("This message won't be displayed");
15} else {
16  console.log("Data type discrepancy detected!"); // this will execute
17}
18
19// Scenario 2: Comparing unknown values (null and undefined)
20let unknownStatus = null;
21let undefinedStatus;  // will automatically be undefined
22
23console.log(unknownStatus == undefinedStatus);  // true (== treats null and undefined as equal)
24console.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:

1// Two dinosaurs with the same traits, but they are different individuals
2let raptor1 = { species: "Velociraptor", age: 3, aggression: "high" };
3let raptor2 = { species: "Velociraptor", age: 3, aggression: "high" };
4
5console.log(raptor1 == raptor2);  // false - different objects in memory
6console.log(raptor1 === raptor2); // false - different objects in memory
7
8// Assigning the same reference
9let raptorReference = raptor1;
10console.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:

1// AND operator (&&) - returns true only when both conditions are true
2let fenceWorking = true;
3let dinoTrackingSystem = true;
4let securityEnsured = fenceWorking && dinoTrackingSystem;
5console.log(securityEnsured); // true - both systems are working
6
7// OR operator (||) - returns true when at least one condition is true
8let mainPower = false;
9let backupPower = true;
10let parkHasPower = mainPower || backupPower;
11console.log(parkHasPower); // true - at least one power source is working
12
13// NOT operator (!) - reverses the boolean value
14let parkClosed = false;
15let parkOpen = !parkClosed;
16console.log(parkOpen); // true - the opposite of closed is open

Complex Logical Conditions

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

1// Can we open the Tyrannosaurus exhibit?
2let weatherSuitable = true;
3let staffPresent = true;
4let powerStable = true;
5let sufficientFoodSupply = false;
6let allDinosaursHealthy = true;
7
8// Opening condition: all factors must be positive
9let canOpenExhibit = weatherSuitable && staffPresent && powerStable &&
10                     sufficientFoodSupply && allDinosaursHealthy;
11console.log(canOpenExhibit); // false - insufficient food supply
12
13// Alarm condition: bad weather OR no power
14let alarmCondition = !weatherSuitable || !powerStable;
15console.log(alarmCondition); // false - no reason for alarm
16
17// Complex condition: if staff present AND (power OR backup generators)
18let backupGeneratorsWorking = true;
19let operationalConditions = staffPresent && (powerStable || backupGeneratorsWorking);
20console.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:

1// Example with && (AND):
2let securitySystem = false;
3let allDinosInEnclosures = checkDinosaurStatus(); // This function won't be called!
4
5function checkDinosaurStatus() {
6  console.log("Checking dinosaur locations...");
7  return true;
8}
9
10// When the first condition is false, the second is not checked
11let parkSafe = securitySystem && allDinosInEnclosures;
12// Nothing will appear in the console, the function is never called
13
14// Example with || (OR):
15let mainPowerSupply = true;
16let backupGenerators = startGenerators(); // This function won't be called!
17
18function startGenerators() {
19  console.log("Starting generators...");
20  return true;
21}
22
23// When the first condition is true, the second is not checked
24let operationalPower = mainPowerSupply || backupGenerators;
25// Nothing will appear in the console, the function is never 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.

1// Jurassic Park examples:
2
3// Checking if a dinosaur has an assigned name
4let dinosaurName = ""; // No name (empty string)
5if (dinosaurName) {
6  console.log("Dinosaur has a name: " + dinosaurName);
7} else {
8  console.log("Dinosaur has no assigned name"); // This will execute
9}
10
11// Checking if a dinosaur identifier exists
12let dinosaurId = 0; // ID 0 (falsy value)
13if (dinosaurId) {
14  console.log("Found dinosaur with ID: " + dinosaurId);
15} else {
16  console.log("No valid dinosaur ID found"); // This will execute
17}
18
19// Checking threat status (null means unknown)
20let threatStatus = null;
21if (threatStatus) {
22  console.log("Threat level: " + threatStatus);
23} else {
24  console.log("Threat status unknown"); // This will execute
25}

Conditional (Ternary) Operator

The conditional operator

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

1// Standard if...else construct
2let enclosureStatus;
3let raptorCount = 5;
4
5if (raptorCount > 0) {
6  enclosureStatus = "Occupied";
7} else {
8  enclosureStatus = "Empty";
9}
10
11// Same thing with the conditional operator
12let enclosureStatus2 = raptorCount > 0 ? "Occupied" : "Empty";
13
14console.log(enclosureStatus);  // "Occupied"
15console.log(enclosureStatus2); // "Occupied"
16
17// More complex example - assigning security level
18let dinosaurSpecies = "Tyrannosaurus";
19let securityLevel = dinosaurSpecies === "Tyrannosaurus" || dinosaurSpecies === "Spinosaurus" ?
20                    "Maximum" :
21                    dinosaurSpecies === "Velociraptor" ?
22                    "High" :
23                    "Standard";
24
25console.log(`For species ${dinosaurSpecies}, required security level: ${securityLevel}`);
26// "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:

1// Dinosaur data structure
2let tyrannosaurus = {
3  name: "Rex",
4  stats: {
5    age: 8,
6    weight: 8000,
7    diet: "carnivore"
8  }
9};
10
11let triceratops = {
12  name: "Tricy",
13  // no stats
14};
15
16// Safely reading nested properties
17console.log(tyrannosaurus.stats?.weight); // 8000
18console.log(triceratops.stats?.weight); // undefined, no error
19
20// Without optional chaining we would get an error:
21// 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:

1// Setting default values for missing data
2let securityReport = {
3  threat: 0,
4  // no power status
5};
6
7// Using ?? to provide a default value when the property is null or undefined
8let threatLevel = securityReport.threat ?? "Unknown";
9let powerStatus = securityReport.power ?? "Undefined";
10
11console.log(threatLevel); // 0 (value 0 is not null or undefined, so it's returned)
12console.log(powerStatus); // "Undefined" (property doesn't exist, so the default is used)
13
14// Comparison with || (OR)
15let threatLevelOr = securityReport.threat || "Unknown";
16console.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 loops, which allow executing code multiple times - essential, for example, when monitoring multiple dinosaur enclosures simultaneously.

Go to CodeWorlds