Conditional statements are the building blocks of decision-making in computer programs. They allow our code to react differently based on whether a certain condition is true or false. Think of it like this: if it's raining, take an umbrella; otherwise, leave it at home. This simple logic is what powers countless features we use every day.
Let's explore some real-world scenarios where conditional statements are indispensable:
- E-commerce and Pricing: Online stores use conditionals to offer discounts. If a customer has a coupon code, apply the discount; otherwise, charge the full price. They can also use conditionals to determine shipping costs based on the order total or destination.
let price = 100;
let hasCoupon = true;
let finalPrice;
if (hasCoupon) {
finalPrice = price * 0.9; // 10% discount
} else {
finalPrice = price;
}
console.log('The final price is: $' + finalPrice);- User Authentication: When you log into a website or app, conditionals are at play. If the username and password match the stored credentials, grant access; otherwise, show an error message.
let enteredUsername = 'user123';
let storedUsername = 'user123';
let enteredPassword = 'password123';
let storedPassword = 'password123';
if (enteredUsername === storedUsername && enteredPassword === storedPassword) {
console.log('Login successful! Welcome!');
} else {
console.log('Invalid username or password. Please try again.');
}- Game Development: Games are rife with conditional logic. For instance, if a player's health drops to zero, the game ends. If a player collects a certain number of coins, they level up. If the player presses the jump button, make the character jump.
graph TD;
A[Player health > 0] --> B{Player presses jump button?};
B -- Yes --> C[Character jumps];
B -- No --> D[Character stays put];
C --> E[Update character position];
D --> E;
E --> F{Game over condition met?};
F -- Yes --> G[End Game];
F -- No --> A;