We use cookies to enhance your experience on the site
CodeWorlds

Conditional Statements (if, else, switch)

In Jurassic Park, security systems and operational protocols must continuously make decisions: what to do when the power level drops below the critical threshold? How to react when the T-Rex approaches the fence? Which procedures to launch for different threat levels?

Similarly, in JavaScript, conditional statements allow making decisions in code based on specific conditions. Let's look at the three main types of conditional statements: if, else if/else, and switch.

The if Statement

The

if
statement is the simplest form of decision-making. It executes a block of code if a specified condition is true.

1// Basic structure of the if statement
2if (condition) {
3  // Code to execute when the condition is true
4}

In practice in Jurassic Park, we can use the

if
statement to check whether additional security measures should be activated:

1// Power level monitoring system for the fence
2let powerLevel = 75; // percent
3let criticalLevel = 30; // percent
4
5if (powerLevel < criticalLevel) {
6  console.log("WARNING! Critical power level. Starting backup generators.");
7  // Code to activate backup generators...
8}
9
10// Dinosaur activity monitoring system
11let tRexDistanceFromFence = 50; // meters
12let safetyThreshold = 10; // meters
13
14if (tRexDistanceFromFence <= safetyThreshold) {
15  console.log("ALERT! T-Rex approaching the fence. Activating additional security.");
16  // Code to increase fence voltage...
17}

if...else Statements

If we want to perform different actions depending on whether a condition is true or false, we use the

if...else
construct.

1// if...else structure
2if (condition) {
3  // Code to execute when the condition is true
4} else {
5  // Code to execute when the condition is false
6}

In Jurassic Park, such a construct can be used to decide whether to open or close an attraction:

1// Attraction availability decision system
2let weatherSuitable = true;
3let safetyIndex = 3; // scale 1-5
4let minimumSafetyLevel = 4;
5
6if (weatherSuitable && safetyIndex >= minimumSafetyLevel) {
7  console.log("The 'Dinosaur Safari' attraction is open to visitors.");
8  // Code to open gates, activate queue...
9} else {
10  console.log("The 'Dinosaur Safari' attraction is temporarily closed for safety reasons.");
11  // Code to close gates, inform staff...
12}

if...else if...else Statements

When we have more than two possible paths of action, we can use the

if...else if...else
construct.

1// if...else if...else structure
2if (condition1) {
3  // Code to execute when condition1 is true
4} else if (condition2) {
5  // Code to execute when condition1 is false but condition2 is true
6} else {
7  // Code to execute when none of the conditions are true
8}

In the context of Jurassic Park, this construct can be applied to a threat warning system with different levels:

1// Threat warning system
2let predatorsOnTheLoose = 0;
3let fenceDamageLevel = 15; // percent
4
5if (predatorsOnTheLoose > 0) {
6  console.log("CODE RED! Immediate evacuation! Predators on the loose!");
7  // Code to launch alarms, evacuation procedures...
8} else if (fenceDamageLevel > 30) {
9  console.log("CODE ORANGE! High risk of dinosaur escape. Prepare for evacuation.");
10  // Code to prepare the park for potential evacuation...
11} else if (fenceDamageLevel > 10) {
12  console.log("CODE YELLOW! Fence damage detected. Send repair team.");
13  // Code to summon technical team...
14} else {
15  console.log("CODE GREEN. All systems functioning properly.");
16  // Normal operation mode...
17}

Nested if Statements

We can also place conditional statements inside other conditional statements. Such nested if statements are useful when we want to check multiple conditions sequentially.

1// Example of nested if statements
2let systemStatus = "operational";
3let accessLevel = "administrator";
4let securityCode = "A123";
5
6if (systemStatus === "operational") {
7  console.log("System is functioning properly.");
8
9  if (accessLevel === "administrator") {
10    console.log("Administrator access granted.");
11
12    if (securityCode === "A123") {
13      console.log("Access to security protocols granted.");
14      // Code to reveal secret security protocols...
15    } else {
16      console.log("Incorrect security code.");
17    }
18  } else {
19    console.log("No administrator privileges.");
20  }
21} else {
22  console.log("System is not functioning properly. Run diagnostics.");
23}

Although nested if statements are sometimes necessary, their excessive use can lead to the so-called "pyramid of doom" (callback hell) or "ladder code," which is hard to read and maintain. In such cases, it's worth considering refactoring the code using the early return approach or switch statements.

The switch Statement

The

switch
statement is an alternative to multiple
if...else if...else
statements, especially when comparing one value with many possible values.

1// Structure of the switch statement
2switch (expression) {
3  case value1:
4    // Code to execute when expression === value1
5    break;
6  case value2:
7    // Code to execute when expression === value2
8    break;
9  // ... more cases
10  default:
11    // Code to execute when no case matches
12}

In Jurassic Park, the

switch
statement can be used to determine protocols for different dinosaur species:

1// Species protocol system
2let dinosaurSpecies = "Velociraptor";
3
4switch (dinosaurSpecies) {
5  case "Tyrannosaurus":
6    console.log("Security protocol T-REX-01: Maximum security level.");
7    console.log("Double electric fence required, constant video monitoring.");
8    break;
9  case "Velociraptor":
10    console.log("Security protocol RAPTOR-02: High security level.");
11    console.log("Reinforced fence required, group activity monitoring.");
12    break;
13  case "Triceratops":
14    console.log("Security protocol HERB-03: Standard security level.");
15    console.log("Basic fence required, herd welfare monitoring.");
16    break;
17  case "Brachiosaurus":
18    console.log("Security protocol HERB-04: Low security level.");
19    console.log("Area marking required, regular food deliveries.");
20    break;
21  default:
22    console.log("Unknown dinosaur species. Apply standard security protocol.");
23    console.log("Contact the paleontology department for species identification.");
24}

The break Statement in switch

Notice that each

case
ends with a
break
statement. This is extremely important because without
break
, code execution will continue through all subsequent cases, regardless of whether they match the expression or not. This property is called "fall-through."

1// Example without break statements - "fall-through"
2let threatLevel = 2; // scale 1-3
3
4switch (threatLevel) {
5  case 3:
6    console.log("Launch park evacuation procedure!");
7    // no break - execution falls through to the next case
8  case 2:
9    console.log("Close all attractions and gather staff.");
10    // no break - execution falls through to the next case
11  case 1:
12    console.log("Increase security system monitoring frequency.");
13    // no break - execution falls through to default
14  default:
15    console.log("Maintain standard security procedures.");
16}
17
18// Result for threatLevel = 2:
19// "Close all attractions and gather staff."
20// "Increase security system monitoring frequency."
21// "Maintain standard security procedures."

Sometimes "fall-through" can be intentional and useful, but most often it's a result of an error. Always make sure you understand and intend such behavior if you omit the

break
statement.

Multiple Cases with the Same Code

One legitimate use of "fall-through" is handling multiple cases with the same code:

1// Grouping cases
2let dayOfWeek = "saturday";
3
4switch (dayOfWeek) {
5  case "monday":
6  case "tuesday":
7  case "wednesday":
8  case "thursday":
9  case "friday":
10    console.log("Jurassic Park open from 9:00 to 18:00.");
11    break;
12  case "saturday":
13  case "sunday":
14    console.log("Jurassic Park open from 8:00 to 20:00 (weekend hours).");
15    break;
16  default:
17    console.log("Invalid day of the week.");
18}

Conditional Expressions (Ternary Operator)

For simple conditions, we can use the conditional operator (also called the ternary operator), which is more concise than an

if...else
statement.

1// Structure of the conditional operator
2condition ? expressionIfTrue : expressionIfFalse

Example use in Jurassic Park:

1// Assigning access level
2let isEmployee = true;
3let accessLevel = isEmployee ? "Full access" : "Visitor access only";
4
5console.log(accessLevel); // "Full access"
6
7// Determining status message
8let visitorCount = 1500;
9let parkCapacity = 2000;
10let entryStatus = visitorCount < parkCapacity
11  ? "Park open - Welcome!"
12  : "Park full - Sorry, ticket sales suspended.";
13
14console.log(entryStatus); // "Park open - Welcome!"

The conditional operator can also be nested, although excessive nesting can reduce code readability:

1// Nested conditional operator
2let dinoSpecies = "Triceratops";
3let age = 5;
4let area = dinoSpecies === "Tyrannosaurus" ? "Sector T"
5         : dinoSpecies === "Velociraptor" ? "Sector V"
6         : dinoSpecies === "Triceratops" ? (age < 3 ? "Young herbivore sector" : "Adult herbivore sector")
7         : "General sector";
8
9console.log(area); // "Adult herbivore sector"

Using Truthy and Falsy Values

As we mentioned in previous lessons, JavaScript treats various values as "truthy" or "falsy" in the context of conditions. We can leverage this property in conditional statements:

1// Checking for value existence
2let dinosaurName = ""; // empty string (falsy)
3let identificationNumber = 0; // zero (falsy)
4let assignedArea = null; // null (falsy)
5let biometricData; // undefined (falsy)
6let speciesRegistered = true; // boolean true (truthy)
7let notes = "Aggressive specimen"; // non-empty string (truthy)
8
9if (dinosaurName) {
10  console.log("Dinosaur name: " + dinosaurName);
11} else {
12  console.log("Dinosaur has no assigned name."); // this will execute
13}
14
15if (identificationNumber) {
16  console.log("ID: " + identificationNumber);
17} else {
18  console.log("No valid ID."); // this will execute
19}
20
21if (speciesRegistered && notes) {
22  console.log("Species registered. Notes: " + notes); // this will execute
23}

Early Return Approach

Sometimes, instead of nesting many

if
statements, it's better to use the early return approach, especially in functions. It involves quickly returning a result as soon as we identify a condition that allows it.

1// Function checking if a dinosaur can be moved to the public enclosure
2function isSuitableForPublicEnclosure(dinosaur) {
3  // Early returns for excluding conditions
4  if (dinosaur.aggressionLevel > 3) {
5    return false; // Too aggressive
6  }
7
8  if (dinosaur.age < 2) {
9    return false; // Too young
10  }
11
12  if (dinosaur.diseases.length > 0) {
13    return false; // Has health issues
14  }
15
16  if (dinosaur.isCarnivore) {
17    // Additional conditions for carnivores
18    if (dinosaur.trained && dinosaur.aggressionLevel <= 2) {
19      return true; // Trained carnivore with low aggression
20    } else {
21      return false; // Untrained or too aggressive carnivore
22    }
23  }
24
25  // By default, herbivores are admitted to the public enclosure
26  return true;
27}
28
29// Example usage
30let triceratops = {
31  species: "Triceratops",
32  aggressionLevel: 2,
33  age: 5,
34  diseases: [],
35  isCarnivore: false,
36  trained: false
37};
38
39let velociraptor = {
40  species: "Velociraptor",
41  aggressionLevel: 4,
42  age: 3,
43  diseases: [],
44  isCarnivore: true,
45  trained: true
46};
47
48console.log(isSuitableForPublicEnclosure(triceratops)); // true
49console.log(isSuitableForPublicEnclosure(velociraptor)); // false

Summary

Conditional statements in JavaScript, much like the decision-making systems in Jurassic Park, allow you to:

  1. Execute code only when specific conditions are met (
    if
    )
  2. Execute different blocks of code depending on conditions (
    if...else
    ,
    if...else if...else
    )
  3. Select one block of code from many based on a value (
    switch
    )
  4. Return different values based on a condition (conditional operator
    ? :
    )
  5. Efficiently manage complex logic (early return, nested conditions)

Choosing the right conditional structure depends on the specific use case, but generally you should aim to:

  • Use
    if...else
    for simple binary conditions
  • Use
    if...else if...else
    for several related conditions
  • Use
    switch
    when comparing one value with many possible values
  • Use the conditional operator for simple, single-line conditions
  • Avoid excessive nesting that reduces code readability

Just as the security systems in Jurassic Park must make the right decisions to ensure safety, we as programmers must make the right decisions about our code structure to ensure its reliability and readability.

In the next lesson, we will look at loops, which allow executing code multiple times - essential, for example, when processing data about many dinosaurs simultaneously.

Go to CodeWorlds