JavaScript and TypeScript course ยท Module 1: JavaScript Basics
Conditional Statements (if, else, switch)
In this lesson9
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.
// Basic structure of the if statement
if (condition) {
// Code to execute when the condition is true
}In practice in Jurassic Park, we can use the if statement to check whether additional security measures should be activated:
// Power level monitoring system for the fence
let powerLevel = 75; // percent
let criticalLevel = 30; // percent
if (powerLevel < criticalLevel) {
console.log("WARNING! Critical power level. Starting backup generators.");
// Code to activate backup generators...
}
// Dinosaur activity monitoring system
let tRexDistanceFromFence = 50; // meters
let safetyThreshold = 10; // meters
if (tRexDistanceFromFence <= safetyThreshold) {
console.log("ALERT! T-Rex approaching the fence. Activating additional security.");
// Code to increase fence voltage...
}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.
// if...else structure
if (condition) {
// Code to execute when the condition is true
} else {
// Code to execute when the condition is false
}In Jurassic Park, such a construct can be used to decide whether to open or close an attraction:
// Attraction availability decision system
let weatherSuitable = true;
let safetyIndex = 3; // scale 1-5
let minimumSafetyLevel = 4;
if (weatherSuitable && safetyIndex >= minimumSafetyLevel) {
console.log("The 'Dinosaur Safari' attraction is open to visitors.");
// Code to open gates, activate queue...
} else {
console.log("The 'Dinosaur Safari' attraction is temporarily closed for safety reasons.");
// Code to close gates, inform staff...
}if...else if...else Statements
When we have more than two possible paths of action, we can use the if...else if...else construct.
// if...else if...else structure
if (condition1) {
// Code to execute when condition1 is true
} else if (condition2) {
// Code to execute when condition1 is false but condition2 is true
} else {
// Code to execute when none of the conditions are true
}In the context of Jurassic Park, this construct can be applied to a threat warning system with different levels:
// Threat warning system
let predatorsOnTheLoose = 0;
let fenceDamageLevel = 15; // percent
if (predatorsOnTheLoose > 0) {
console.log("CODE RED! Immediate evacuation! Predators on the loose!");
// Code to launch alarms, evacuation procedures...
} else if (fenceDamageLevel > 30) {
console.log("CODE ORANGE! High risk of dinosaur escape. Prepare for evacuation.");
// Code to prepare the park for potential evacuation...
} else if (fenceDamageLevel > 10) {
console.log("CODE YELLOW! Fence damage detected. Send repair team.");
// Code to summon technical team...
} else {
console.log("CODE GREEN. All systems functioning properly.");
// Normal operation mode...
}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.
// Example of nested if statements
let systemStatus = "operational";
let accessLevel = "administrator";
let securityCode = "A123";
if (systemStatus === "operational") {
console.log("System is functioning properly.");
if (accessLevel === "administrator") {
console.log("Administrator access granted.");
if (securityCode === "A123") {
console.log("Access to security protocols granted.");
// Code to reveal secret security protocols...
} else {
console.log("Incorrect security code.");
}
} else {
console.log("No administrator privileges.");
}
} else {
console.log("System is not functioning properly. Run diagnostics.");
}Although nested if statements are sometimes necessary, their excessive use can lead to the so-called "pyramid of doom" 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.
// Structure of the switch statement
switch (expression) {
case value1:
// Code to execute when expression === value1
break;
case value2:
// Code to execute when expression === value2
break;
// ... more cases
default:
// Code to execute when no case matches
}In Jurassic Park, the switch statement can be used to determine protocols for different dinosaur species:
// Species protocol system
let dinosaurSpecies = "Velociraptor";
switch (dinosaurSpecies) {
case "Tyrannosaurus":
console.log("Security protocol T-REX-01: Maximum security level.");
console.log("Double electric fence required, constant video monitoring.");
break;
case "Velociraptor":
console.log("Security protocol RAPTOR-02: High security level.");
console.log("Reinforced fence required, group activity monitoring.");
break;
case "Triceratops":
console.log("Security protocol HERB-03: Standard security level.");
console.log("Basic fence required, herd welfare monitoring.");
break;
case "Brachiosaurus":
console.log("Security protocol HERB-04: Low security level.");
console.log("Area marking required, regular food deliveries.");
break;
default:
console.log("Unknown dinosaur species. Apply standard security protocol.");
console.log("Contact the paleontology department for species identification.");
}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."
// Example without break statements - "fall-through"
let threatLevel = 2; // scale 1-3
switch (threatLevel) {
case 3:
console.log("Launch park evacuation procedure!");
// no break - execution falls through to the next case
case 2:
console.log("Close all attractions and gather staff.");
// no break - execution falls through to the next case
case 1:
console.log("Increase security system monitoring frequency.");
// no break - execution falls through to default
default:
console.log("Maintain standard security procedures.");
}
// Result for threatLevel = 2:
// "Close all attractions and gather staff."
// "Increase security system monitoring frequency."
// "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:
// Grouping cases
let dayOfWeek = "saturday";
switch (dayOfWeek) {
case "monday":
case "tuesday":
case "wednesday":
case "thursday":
case "friday":
console.log("Jurassic Park open from 9:00 to 18:00.");
break;
case "saturday":
case "sunday":
console.log("Jurassic Park open from 8:00 to 20:00 (weekend hours).");
break;
default:
console.log("Invalid day of the week.");
}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.
// Structure of the conditional operator
condition ? expressionIfTrue : expressionIfFalseExample use in Jurassic Park:
// Assigning access level
let isEmployee = true;
let accessLevel = isEmployee ? "Full access" : "Visitor access only";
console.log(accessLevel); // "Full access"
// Determining status message
let visitorCount = 1500;
let parkCapacity = 2000;
let entryStatus = visitorCount < parkCapacity
? "Park open - Welcome!"
: "Park full - Sorry, ticket sales suspended.";
console.log(entryStatus); // "Park open - Welcome!"The conditional operator can also be nested, although excessive nesting can reduce code readability:
// Nested conditional operator
let dinoSpecies = "Triceratops";
let age = 5;
let area = dinoSpecies === "Tyrannosaurus" ? "Sector T"
: dinoSpecies === "Velociraptor" ? "Sector V"
: dinoSpecies === "Triceratops" ? (age < 3 ? "Young herbivore sector" : "Adult herbivore sector")
: "General sector";
console.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:
// Checking for value existence
let dinosaurName = ""; // empty string (falsy)
let identificationNumber = 0; // zero (falsy)
let assignedArea = null; // null (falsy)
let biometricData; // undefined (falsy)
let speciesRegistered = true; // boolean true (truthy)
let notes = "Aggressive specimen"; // non-empty string (truthy)
if (dinosaurName) {
console.log("Dinosaur name: " + dinosaurName);
} else {
console.log("Dinosaur has no assigned name."); // this will execute
}
if (identificationNumber) {
console.log("ID: " + identificationNumber);
} else {
console.log("No valid ID."); // this will execute
}
if (speciesRegistered && notes) {
console.log("Species registered. Notes: " + notes); // this will execute
}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.
// Function checking if a dinosaur can be moved to the public enclosure
function isSuitableForPublicEnclosure(dinosaur) {
// Early returns for excluding conditions
if (dinosaur.aggressionLevel > 3) {
return false; // Too aggressive
}
if (dinosaur.age < 2) {
return false; // Too young
}
if (dinosaur.diseases.length > 0) {
return false; // Has health issues
}
if (dinosaur.isCarnivore) {
// Additional conditions for carnivores
if (dinosaur.trained && dinosaur.aggressionLevel <= 2) {
return true; // Trained carnivore with low aggression
} else {
return false; // Untrained or too aggressive carnivore
}
}
// By default, herbivores are admitted to the public enclosure
return true;
}
// Example usage
let triceratops = {
species: "Triceratops",
aggressionLevel: 2,
age: 5,
diseases: [],
isCarnivore: false,
trained: false
};
let velociraptor = {
species: "Velociraptor",
aggressionLevel: 4,
age: 3,
diseases: [],
isCarnivore: true,
trained: true
};
console.log(isSuitableForPublicEnclosure(triceratops)); // true
console.log(isSuitableForPublicEnclosure(velociraptor)); // falseSummary
Conditional statements in JavaScript, much like the decision-making systems in Jurassic Park, allow you to:
- Execute code only when specific conditions are met (
if) - Execute different blocks of code depending on conditions (
if...else,if...else if...else) - Select one block of code from many based on a value (
switch) - Return different values based on a condition (conditional operator
? :) - 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...elsefor simple binary conditions - Use
if...else if...elsefor several related conditions - Use
switchwhen 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.
Code for this lesson: index.js
// Conditional statements - park decision system
// Use if/else and switch to make decisions
// === if / else if / else ===
console.log("=== Security system ===");
let threatLevel = 3; // Change the value and observe the result!
if (threatLevel >= 5) {
console.log("CRITICAL ALARM! Evacuation!");
} else if (threatLevel >= 3) {
console.log("WARNING! Elevated threat level.");
} else if (threatLevel >= 1) {
console.log("CAUTION: Monitoring the situation.");
} else {
console.log("Status: Normal. Park is safe.");
}
// === Nested conditions ===
console.log("\n=== Dinosaur classification ===");
let diet = "carnivore";
let weight = 7000; // kg
if (diet === "carnivore") {
if (weight > 5000) {
console.log("Category: CRITICAL THREAT");
} else {
console.log("Category: HIGH THREAT");
}
} else {
if (weight > 10000) {
console.log("Category: MEDIUM THREAT (large herbivore)");
} else {
console.log("Category: LOW THREAT");
}
}
// === switch ===
console.log("\n=== Sector protocol ===");
let sector = "B"; // Change to A, B, C, D
switch (sector) {
case "A":
console.log("Sector A: Carnivores - maximum security");
break;
case "B":
console.log("Sector B: Herbivores - standard security");
break;
case "C":
console.log("Sector C: Birds - protective nets");
break;
case "D":
console.log("Sector D: Marine reptiles - closed pools");
break;
default:
console.log("Unknown sector!");
}
// Your task:
// 1. Change variable values and observe different paths
// 2. Add new conditions to the switch statement
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. Which code block will execute when the condition in an if statement is false?
Hands-on tasks in the game
- Code editor
Store the voltage of two fences: const voltageTRex = 10000 and const voltageRaptor = 3000. For each fence use if/else: if the voltage is greater than 8000, display 'ACTIVE' in the console, otherwise 'ALARM'.
- Horizontal ordering
Arrange the conditional statement elements:
- Code editor
Store the dinosaur's distance from the fence in metres in a variable dinoDistance (e.g. 5). Using if / else if / else, display in the console: 'RED ALERT' when the distance is less than 3, 'WARNING' when it is less than 10, and 'SAFE' otherwise.
- Click in order
Arrange the if statement elements in the correct order: