Master decision-making in JavaScript with if/else statements, switch cases, and conditional operators. Learn to create dynamic programs that respond intelligently to different conditions.
Control flow is the foundation of intelligent programming. It's what makes your JavaScript programs capable of making decisions, responding to different situations, and creating dynamic, interactive experiences.
Think of control flow like the decision-making process in everyday life. When you check the weather app, you might decide to bring an umbrella if it's raining, wear a jacket if it's cold, or shorts if it's sunny. Similarly, your JavaScript programs need to make decisions based on data and user interactions.
In this comprehensive lesson, you'll learn how to write JavaScript that thinks and adapts, creating programs that can handle multiple scenarios and provide intelligent responses to any situation.
Conditional logic allows programs to execute different code blocks based on whether certain conditions are true or false. This is fundamental to creating intelligent, responsive applications.
Why Conditionals Are Essential:
Real-World Applications:
The Foundation of Interactive Programming:
Without conditionals, programs would be linear and predictable, executing the same code every time. Conditionals make programs dynamic, allowing them to adapt and respond intelligently to changing conditions and user inputs.
The if/else statement is the most fundamental conditional structure in JavaScript. It allows your program to choose between different paths of execution.
Basic If Statement:
1let temperature = 75;
2
3if (temperature > 70) {
4 console.log("It's warm outside!");
5 console.log("Perfect weather for outdoor activities.");
6}If/Else Statement:
1let userAge = 17;
2
3if (userAge >= 18) {
4 console.log("You can vote in the election.");
5 console.log("Don't forget to register!");
6} else {
7 console.log("You're not old enough to vote yet.");
8 console.log(`You can vote in ${18 - userAge} years.`);
9}If/Else If/Else Chain:
1let grade = 87;
2let letterGrade;
3
4if (grade >= 90) {
5 letterGrade = "A";
6 console.log("Excellent work!");
7} else if (grade >= 80) {
8 letterGrade = "B";
9 console.log("Good job!");
10} else if (grade >= 70) {
11 letterGrade = "C";
12 console.log("Satisfactory performance.");
13} else if (grade >= 60) {
14 letterGrade = "D";
15 console.log("Needs improvement.");
16} else {
17 letterGrade = "F";
18 console.log("Please see your instructor.");
19}
20
21console.log(`Your letter grade is: ${letterGrade}`);Best Practices for If/Else Statements:
Common Patterns:
1// Checking for null or undefined
2if (user !== null && user !== undefined) {
3 console.log(`Welcome, ${user.name}!`);
4} else {
5 console.log("Please log in to continue.");
6}
7
8// Validating input
9if (password.length >= 8) {
10 console.log("Password meets requirements.");
11} else {
12 console.log("Password must be at least 8 characters long.");
13}
14
15// Checking multiple conditions
16if (isLoggedIn && hasPermission && !isBlocked) {
17 showAdminPanel();
18} else {
19 showAccessDeniedMessage();
20}Comparison operators are used to compare values and return true or false. They're essential for creating conditions in your if statements and other control structures.
Equality Operators:
Strict Equality (===) - Recommended:
1let age = 25;
2let ageString = "25";
3
4console.log(age === 25); // true
5console.log(age === ageString); // false (different types)
6console.log(age === "25"); // false (different types)
7
8// Always use === to avoid unexpected behavior
9if (userInput === "yes") {
10 processConfirmation();
11}Loose Equality (==) - Avoid:
1console.log(25 == "25"); // true (type conversion happens)
2console.log(0 == false); // true (unexpected!)
3console.log("" == false); // true (unexpected!)
4
5// This can cause bugs - avoid using ==Inequality Operators:
1let score = 85;
2let passingScore = 70;
3
4// Strict inequality
5console.log(score !== passingScore); // true
6
7// Greater than / Less than
8console.log(score > passingScore); // true
9console.log(score < 100); // true
10
11// Greater than or equal / Less than or equal
12console.log(score >= 85); // true
13console.log(score <= 90); // trueRelational Operators in Practice:
1// Age verification system
2function checkAgeCategory(age) {
3 if (age < 13) {
4 return "child";
5 } else if (age < 18) {
6 return "teen";
7 } else if (age < 65) {
8 return "adult";
9 } else {
10 return "senior";
11 }
12}
13
14// Price comparison for discounts
15function calculateDiscount(originalPrice, membershipLevel) {
16 if (originalPrice >= 100 && membershipLevel === "premium") {
17 return originalPrice * 0.2; // 20% discount
18 } else if (originalPrice >= 50 && membershipLevel === "gold") {
19 return originalPrice * 0.15; // 15% discount
20 } else if (originalPrice >= 25) {
21 return originalPrice * 0.1; // 10% discount
22 } else {
23 return 0; // No discount
24 }
25}String Comparisons:
1let firstName = "Alice";
2let lastName = "Johnson";
3
4// String equality
5if (firstName === "Alice") {
6 console.log("Hello Alice!");
7}
8
9// Alphabetical comparison
10if (firstName < lastName) {
11 console.log("First name comes before last name alphabetically");
12}
13
14// Case-sensitive comparisons
15console.log("apple" === "Apple"); // false
16console.log("apple" === "apple"); // true
17
18// Case-insensitive comparison
19function compareIgnoreCase(str1, str2) {
20 return str1.toLowerCase() === str2.toLowerCase();
21}Common Comparison Pitfalls:
1// Comparing with null/undefined
2let data = null;
3if (data !== null && data !== undefined) {
4 console.log(data.property);
5}
6
7// Better approach using nullish coalescing
8if (data != null) { // Checks for both null and undefined
9 console.log(data.property);
10}
11
12// NaN comparisons (special case)
13let result = parseInt("abc");
14console.log(result === NaN); // false (never true!)
15console.log(Number.isNaN(result)); // true (correct way)Logical operators allow you to combine multiple conditions to create more sophisticated decision-making logic. They're essential for handling complex scenarios in real applications.
AND Operator (&&) - All Must Be True:
1let hasAccount = true;
2let isEmailVerified = true;
3let hasValidPayment = false;
4
5// All conditions must be true
6if (hasAccount && isEmailVerified && hasValidPayment) {
7 console.log("Welcome to premium features!");
8} else {
9 console.log("Please complete your account setup.");
10}
11
12// Practical example: Form validation
13function validateRegistration(email, password, age, termsAccepted) {
14 if (email.length > 0 &&
15 password.length >= 8 &&
16 age >= 18 &&
17 termsAccepted === true) {
18 return "Registration valid";
19 } else {
20 return "Please complete all requirements";
21 }
22}OR Operator (||) - Any Can Be True:
1let isWeekend = true;
2let isHoliday = false;
3let isVacationDay = false;
4
5// Any condition can be true
6if (isWeekend || isHoliday || isVacationDay) {
7 console.log("No work today!");
8} else {
9 console.log("Time to work!");
10}
11
12// Practical example: Multiple payment methods
13function canProcessPayment(hasCreditCard, hasPayPal, hasGiftCard, hasBalance) {
14 if (hasCreditCard || hasPayPal || hasGiftCard || hasBalance) {
15 return "Payment method available";
16 } else {
17 return "Please add a payment method";
18 }
19}NOT Operator (!) - Opposite Logic:
1let isLoggedIn = false;
2let hasPermission = true;
3
4// NOT operator flips the boolean value
5if (!isLoggedIn) {
6 console.log("Please log in to continue");
7 showLoginForm();
8}
9
10if (!hasPermission) {
11 console.log("Access denied");
12 redirectToHomePage();
13}
14
15// Double NOT (!!) converts to boolean
16let truthyValue = "Hello";
17let falsyValue = "";
18
19console.log(!!truthyValue); // true
20console.log(!!falsyValue); // falseComplex Logical Combinations:
1// E-commerce checkout validation
2function canCompleteCheckout(user, cart, paymentMethod) {
3 const hasItems = cart.length > 0;
4 const hasValidPayment = paymentMethod !== null;
5 const isUserVerified = user && user.emailVerified;
6 const hasShippingAddress = user && user.address && user.address.length > 0;
7
8 // Complex condition combining multiple factors
9 if (hasItems &&
10 hasValidPayment &&
11 isUserVerified &&
12 (hasShippingAddress || cart.every(item => item.type === 'digital'))) {
13 return { success: true, message: "Ready to checkout!" };
14 } else {
15 let errors = [];
16 if (!hasItems) errors.push("Cart is empty");
17 if (!hasValidPayment) errors.push("No payment method");
18 if (!isUserVerified) errors.push("Email not verified");
19 if (!hasShippingAddress) errors.push("No shipping address");
20
21 return { success: false, errors: errors };
22 }
23}Short-Circuit Evaluation:
1// && stops at first false value
2let user = null;
3user && user.name && console.log(user.name); // Safe navigation
4
5// || provides default values
6let userName = user?.name || "Guest User";
7let theme = localStorage.getItem('theme') || 'light';
8
9// Practical short-circuit patterns
10function greetUser(user) {
11 // Only execute if user exists
12 user && user.name && console.log(`Hello, ${user.name}!`);
13
14 // Provide fallback values
15 const displayName = user?.name || user?.email || "Anonymous";
16 const preferences = user?.preferences || getDefaultPreferences();
17
18 return {
19 displayName,
20 preferences
21 };
22}Operator Precedence:
1// AND (&&) has higher precedence than OR (||)
2let a = true, b = false, c = true;
3
4// This evaluates as: a || (b && c)
5console.log(a || b && c); // true
6
7// Use parentheses for clarity
8console.log((a || b) && c); // true
9console.log(a || (b && c)); // true
10
11// Best practice: Always use parentheses for complex conditions
12if ((userAge >= 18 && hasParentalConsent) || (userAge >= 21)) {
13 allowAccess();
14}Switch statements provide an elegant way to handle multiple possible values for a single variable. They're more readable than long if/else chains when dealing with discrete values.
Basic Switch Statement:
1let dayOfWeek = 3;
2let dayName;
3
4switch (dayOfWeek) {
5 case 1:
6 dayName = "Monday";
7 break;
8 case 2:
9 dayName = "Tuesday";
10 break;
11 case 3:
12 dayName = "Wednesday";
13 break;
14 case 4:
15 dayName = "Thursday";
16 break;
17 case 5:
18 dayName = "Friday";
19 break;
20 case 6:
21 dayName = "Saturday";
22 break;
23 case 7:
24 dayName = "Sunday";
25 break;
26 default:
27 dayName = "Invalid day";
28 break;
29}
30
31console.log(dayName); // "Wednesday"Switch with String Values:
1function processUserAction(action) {
2 switch (action.toLowerCase()) {
3 case 'login':
4 return handleLogin();
5 case 'logout':
6 return handleLogout();
7 case 'register':
8 return handleRegistration();
9 case 'forgot-password':
10 return handlePasswordReset();
11 case 'update-profile':
12 return handleProfileUpdate();
13 default:
14 return { error: "Unknown action" };
15 }
16}
17
18// Usage
19let result = processUserAction('LOGIN'); // Case insensitiveFall-Through Cases (No Break):
1function getSeasonFromMonth(month) {
2 let season;
3
4 switch (month) {
5 case 12:
6 case 1:
7 case 2:
8 season = "Winter";
9 break;
10 case 3:
11 case 4:
12 case 5:
13 season = "Spring";
14 break;
15 case 6:
16 case 7:
17 case 8:
18 season = "Summer";
19 break;
20 case 9:
21 case 10:
22 case 11:
23 season = "Fall";
24 break;
25 default:
26 season = "Invalid month";
27 break;
28 }
29
30 return season;
31}
32
33console.log(getSeasonFromMonth(4)); // "Spring"Switch vs If/Else Comparison:
1// Using if/else (can become verbose)
2function getGradeMessage(letter) {
3 if (letter === 'A') {
4 return "Excellent work!";
5 } else if (letter === 'B') {
6 return "Good job!";
7 } else if (letter === 'C') {
8 return "Satisfactory.";
9 } else if (letter === 'D') {
10 return "Needs improvement.";
11 } else if (letter === 'F') {
12 return "Please see instructor.";
13 } else {
14 return "Invalid grade.";
15 }
16}
17
18// Using switch (cleaner for multiple discrete values)
19function getGradeMessageSwitch(letter) {
20 switch (letter) {
21 case 'A':
22 return "Excellent work!";
23 case 'B':
24 return "Good job!";
25 case 'C':
26 return "Satisfactory.";
27 case 'D':
28 return "Needs improvement.";
29 case 'F':
30 return "Please see instructor.";
31 default:
32 return "Invalid grade.";
33 }
34}Advanced Switch Patterns:
1// Using switch with expressions
2function calculateShipping(method, weight, distance) {
3 let baseCost;
4
5 switch (method) {
6 case 'standard':
7 baseCost = 5.99;
8 break;
9 case 'express':
10 baseCost = 12.99;
11 break;
12 case 'overnight':
13 baseCost = 24.99;
14 break;
15 case 'same-day':
16 baseCost = 39.99;
17 break;
18 default:
19 throw new Error("Invalid shipping method");
20 }
21
22 // Additional calculations based on switch result
23 return baseCost + (weight * 0.5) + (distance * 0.1);
24}
25
26// Switch with function calls
27function handleAPIResponse(statusCode) {
28 switch (statusCode) {
29 case 200:
30 case 201:
31 case 204:
32 return handleSuccess();
33 case 400:
34 return handleBadRequest();
35 case 401:
36 return handleUnauthorized();
37 case 403:
38 return handleForbidden();
39 case 404:
40 return handleNotFound();
41 case 500:
42 case 502:
43 case 503:
44 return handleServerError();
45 default:
46 return handleUnknownError(statusCode);
47 }
48}When to Use Switch vs If/Else:
Experience JavaScript conditional logic with this comprehensive demonstration. Explore if/else statements, comparison operators, logical operators, and switch statements through real-world interactive examples.
1<!DOCTYPE html>
2<html lang="en">
3<head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1.0">
6 <title>Control Flow & Conditionals Demo</title>
7 <style>
8 body {
9 font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
10 max-width: 900px;
11 margin: 0 auto;
12 padding: 20px;
13 background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
14 color: white;
15 min-height: 100vh;
16 }
17
18 .container {
19 background: rgba(255, 255, 255, 0.1);
20 backdrop-filter: blur(10px);
21 border-radius: 20px;
22 padding: 30px;
23 box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
24 border: 1px solid rgba(255, 255, 255, 0.2);
25 }
26
27 h1 {
28 text-align: center;
29 margin-bottom: 30px;
30 font-size: 2.5rem;
31 text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
32 }
33
34 .demo-section {
35 margin: 25px 0;
36 padding: 20px;
37 background: rgba(255, 255, 255, 0.1);
38 border-radius: 15px;
39 border-left: 4px solid #ffd700;
40 }
41
42 h2 {
43 color: #ffd700;
44 margin-top: 0;
45 font-size: 1.5rem;
46 }
47
48 .interactive-area {
49 background: rgba(255, 255, 255, 0.15);
50 padding: 20px;
51 border-radius: 12px;
52 margin: 15px 0;
53 border: 2px solid rgba(255, 215, 0, 0.3);
54 }
55
56 button {
57 background: linear-gradient(45deg, #ffd700, #ffed4e);
58 color: #333;
59 border: none;
60 padding: 12px 24px;
61 margin: 8px;
62 border-radius: 25px;
63 cursor: pointer;
64 font-weight: bold;
65 font-size: 14px;
66 transition: all 0.3s ease;
67 box-shadow: 0 4px 15px rgba(255, 215, 0, 0.3);
68 }
69
70 button:hover {
71 transform: translateY(-2px);
72 box-shadow: 0 6px 20px rgba(255, 215, 0, 0.4);
73 }
74
75 button:active {
76 transform: translateY(0);
77 }
78
79 input, select {
80 padding: 10px 15px;
81 border: 2px solid rgba(255, 255, 255, 0.3);
82 border-radius: 20px;
83 background: rgba(255, 255, 255, 0.1);
84 color: white;
85 font-size: 16px;
86 margin: 5px;
87 backdrop-filter: blur(5px);
88 }
89
90 input::placeholder {
91 color: rgba(255, 255, 255, 0.7);
92 }
93
94 select {
95 cursor: pointer;
96 }
97
98 select option {
99 background: #764ba2;
100 color: white;
101 }
102
103 .output {
104 background: rgba(0, 0, 0, 0.2);
105 padding: 15px;
106 border-radius: 10px;
107 margin: 15px 0;
108 font-family: 'Courier New', monospace;
109 min-height: 40px;
110 border-left: 4px solid #4CAF50;
111 }
112
113 .code-block {
114 background: rgba(0, 0, 0, 0.3);
115 padding: 15px;
116 border-radius: 8px;
117 font-family: 'Courier New', monospace;
118 font-size: 14px;
119 margin: 10px 0;
120 overflow-x: auto;
121 border: 1px solid rgba(255, 255, 255, 0.1);
122 }
123
124 .highlight {
125 background: rgba(255, 215, 0, 0.2);
126 padding: 2px 6px;
127 border-radius: 4px;
128 font-weight: bold;
129 }
130
131 .success { color: #4CAF50; font-weight: bold; }
132 .info { color: #2196F3; font-weight: bold; }
133 .warning { color: #FF9800; font-weight: bold; }
134 .error { color: #f44336; font-weight: bold; }
135
136 .grid {
137 display: grid;
138 grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
139 gap: 15px;
140 margin: 20px 0;
141 }
142
143 .input-group {
144 display: flex;
145 flex-wrap: wrap;
146 align-items: center;
147 gap: 10px;
148 margin: 10px 0;
149 }
150
151 label {
152 font-weight: bold;
153 min-width: 120px;
154 }
155 </style>
156</head>
157<body>
158 <div class="container">
159 <h1>🧠 Control Flow & Conditionals Demo</h1>
160
161 <div class="demo-section">
162 <h2>1. If/Else Statements - Age Category Checker</h2>
163 <p>Explore how if/else statements make decisions based on different conditions:</p>
164
165 <div class="interactive-area">
166 <div class="input-group">
167 <label>Enter Age:</label>
168 <input type="number" id="ageInput" value="25" min="1" max="150">
169 <button onclick="checkAgeCategory()">📊 Check Category</button>
170 </div>
171 <div id="ageOutput" class="output">Enter an age to see conditional logic in action!</div>
172 </div>
173 </div>
174
175 <div class="demo-section">
176 <h2>2. Comparison Operators - Grade Calculator</h2>
177 <p>See how comparison operators evaluate different values:</p>
178
179 <div class="interactive-area">
180 <div class="input-group">
181 <label>Test Score:</label>
182 <input type="number" id="scoreInput" value="87" min="0" max="100">
183 <button onclick="calculateGrade()">📝 Get Grade</button>
184 <button onclick="demonstrateComparisons()">🔍 Show Comparisons</button>
185 </div>
186 <div id="gradeOutput" class="output">Enter a score to see comparison operators at work!</div>
187 </div>
188 </div>
189
190 <div class="demo-section">
191 <h2>3. Logical Operators - Access Control System</h2>
192 <p>Experience how logical operators combine multiple conditions:</p>
193
194 <div class="interactive-area">
195 <div class="grid">
196 <div>
197 <label><input type="checkbox" id="hasAccount" checked> Has Account</label><br>
198 <label><input type="checkbox" id="isVerified" checked> Email Verified</label><br>
199 <label><input type="checkbox" id="hasPayment"> Valid Payment</label><br>
200 <label><input type="checkbox" id="isAdmin"> Admin Rights</label>
201 </div>
202 <div>
203 <button onclick="checkAccess()">🔐 Check Access</button>
204 <button onclick="demonstrateLogical()">⚡ Show Logic</button>
205 </div>
206 </div>
207 <div id="accessOutput" class="output">Adjust the checkboxes to see logical operators in action!</div>
208 </div>
209 </div>
210
211 <div class="demo-section">
212 <h2>4. Switch Statements - Action Handler</h2>
213 <p>Learn how switch statements handle multiple discrete values efficiently:</p>
214
215 <div class="interactive-area">
216 <div class="input-group">
217 <label>Select Action:</label>
218 <select id="actionSelect">
219 <option value="login">Login</option>
220 <option value="logout">Logout</option>
221 <option value="register">Register</option>
222 <option value="forgot-password">Forgot Password</option>
223 <option value="update-profile">Update Profile</option>
224 <option value="delete-account">Delete Account</option>
225 <option value="invalid-action">Invalid Action</option>
226 </select>
227 <button onclick="processAction()">⚙️ Process Action</button>
228 </div>
229
230 <div class="input-group">
231 <label>Day Number:</label>
232 <input type="number" id="dayInput" value="3" min="1" max="7">
233 <button onclick="getDayName()">📅 Get Day Name</button>
234 </div>
235
236 <div id="switchOutput" class="output">Use the controls above to see switch statements in action!</div>
237 </div>
238 </div>
239
240 <div class="demo-section">
241 <h2>5. Complex Conditions - E-commerce Discount Calculator</h2>
242 <p>See how multiple conditions work together in real-world scenarios:</p>
243
244 <div class="interactive-area">
245 <div class="grid">
246 <div>
247 <div class="input-group">
248 <label>Cart Total: $</label>
249 <input type="number" id="cartTotal" value="75" min="0" step="0.01">
250 </div>
251 <div class="input-group">
252 <label>Membership:</label>
253 <select id="membershipType">
254 <option value="none">None</option>
255 <option value="bronze">Bronze</option>
256 <option value="silver">Silver</option>
257 <option value="gold">Gold</option>
258 <option value="platinum">Platinum</option>
259 </select>
260 </div>
261 </div>
262 <div>
263 <div class="input-group">
264 <label><input type="checkbox" id="isFirstTime"> First-time Customer</label><br>
265 <label><input type="checkbox" id="hasPromoCode"> Has Promo Code</label><br>
266 <label><input type="checkbox" id="isBirthday"> Birthday Month</label>
267 </div>
268 <button onclick="calculateDiscount()">💰 Calculate Discount</button>
269 </div>
270 </div>
271 <div id="discountOutput" class="output">Adjust the settings to see complex conditional logic!</div>
272 </div>
273 </div>
274
275 <div class="demo-section">
276 <h2>6. Weather Decision System</h2>
277 <p>Real-world conditional logic for weather-based recommendations:</p>
278
279 <div class="interactive-area">
280 <div class="input-group">
281 <label>Temperature (°F):</label>
282 <input type="number" id="temperature" value="72" min="-50" max="150">
283
284 <label>Weather:</label>
285 <select id="weatherCondition">
286 <option value="sunny">Sunny</option>
287 <option value="cloudy">Cloudy</option>
288 <option value="rainy">Rainy</option>
289 <option value="snowy">Snowy</option>
290 <option value="stormy">Stormy</option>
291 </select>
292
293 <label>Wind (mph):</label>
294 <input type="number" id="windSpeed" value="5" min="0" max="100">
295
296 <button onclick="getWeatherAdvice()">🌤️ Get Advice</button>
297 </div>
298 <div id="weatherOutput" class="output">Set weather conditions to get personalized recommendations!</div>
299 </div>
300 </div>
301
302 <div class="demo-section">
303 <h2>🎯 Interactive Challenges</h2>
304 <p>Test your understanding with these interactive challenges:</p>
305
306 <div class="interactive-area">
307 <div class="grid">
308 <div>
309 <h3>Challenge 1: Password Strength</h3>
310 <input type="text" id="passwordInput" placeholder="Enter password">
311 <button onclick="checkPasswordStrength()">🔒 Check Strength</button>
312 </div>
313 <div>
314 <h3>Challenge 2: Number Classifier</h3>
315 <input type="number" id="numberInput" placeholder="Enter number">
316 <button onclick="classifyNumber()">🔢 Classify</button>
317 </div>
318 </div>
319 <div id="challengeOutput" class="output">Try the challenges above to practice conditional logic!</div>
320 </div>
321 </div>
322 </div>
323
324 <script>
325 // Control Flow & Conditionals Demo Script
326
327 // 1. AGE CATEGORY CHECKER - If/Else Statements
328 function checkAgeCategory() {
329 const age = parseInt(document.getElementById('ageInput').value) || 0;
330 let category, description, privileges = [];
331
332 if (age <= 0) {
333 category = "Invalid";
334 description = "Please enter a valid age";
335 } else if (age < 13) {
336 category = "Child";
337 description = "Childhood is about learning and play";
338 privileges = ["Parental guidance required", "Educational content", "Safe online spaces"];
339 } else if (age < 18) {
340 category = "Teenager";
341 description = "Time for growth and discovery";
342 privileges = ["Social media access", "Educational resources", "Some independence"];
343 } else if (age < 21) {
344 category = "Young Adult";
345 description = "Building independence and responsibility";
346 privileges = ["Voting rights", "Most adult activities", "College opportunities"];
347 } else if (age < 65) {
348 category = "Adult";
349 description = "Full adult responsibilities and freedoms";
350 privileges = ["All legal rights", "Career opportunities", "Full independence"];
351 } else {
352 category = "Senior";
353 description = "Wisdom and experience guide the way";
354 privileges = ["Senior discounts", "Retirement benefits", "Respect and honor"];
355 }
356
357 document.getElementById('ageOutput').innerHTML = `375`;
376 }
377
378 // 2. GRADE CALCULATOR - Comparison Operators
379 function calculateGrade() {
380 const score = parseInt(document.getElementById('scoreInput').value) || 0;
381 let letterGrade, gpa, message;
382
383 if (score >= 97) {
384 letterGrade = "A+";
385 gpa = 4.0;
386 message = "Outstanding! Exceptional performance!";
387 } else if (score >= 93) {
388 letterGrade = "A";
389 gpa = 4.0;
390 message = "Excellent work! You've mastered the material!";
391 } else if (score >= 90) {
392 letterGrade = "A-";
393 gpa = 3.7;
394 message = "Great job! Very strong performance!";
395 } else if (score >= 87) {
396 letterGrade = "B+";
397 gpa = 3.3;
398 message = "Good work! Above average performance!";
399 } else if (score >= 83) {
400 letterGrade = "B";
401 gpa = 3.0;
402 message = "Solid performance! You understand the concepts well!";
403 } else if (score >= 80) {
404 letterGrade = "B-";
405 gpa = 2.7;
406 message = "Good effort! Room for improvement!";
407 } else if (score >= 77) {
408 letterGrade = "C+";
409 gpa = 2.3;
410 message = "Satisfactory work! Keep studying!";
411 } else if (score >= 73) {
412 letterGrade = "C";
413 gpa = 2.0;
414 message = "Average performance! More practice needed!";
415 } else if (score >= 70) {
416 letterGrade = "C-";
417 gpa = 1.7;
418 message = "Passing grade! Focus on improvement!";
419 } else if (score >= 67) {
420 letterGrade = "D+";
421 gpa = 1.3;
422 message = "Below average! Seek help from instructor!";
423 } else if (score >= 63) {
424 letterGrade = "D";
425 gpa = 1.0;
426 message = "Minimum passing! Immediate attention required!";
427 } else if (score >= 60) {
428 letterGrade = "D-";
429 gpa = 0.7;
430 message = "Barely passing! Must improve significantly!";
431 } else {
432 letterGrade = "F";
433 gpa = 0.0;
434 message = "Failing grade! Please see your instructor immediately!";
435 }
436
437 document.getElementById('gradeOutput').innerHTML = `455`;
456 }
457
458 function demonstrateComparisons() {
459 const score = parseInt(document.getElementById('scoreInput').value) || 0;
460
461 document.getElementById('gradeOutput').innerHTML = `475`;
476 }
477
478 // 3. ACCESS CONTROL - Logical Operators
479 function checkAccess() {
480 const hasAccount = document.getElementById('hasAccount').checked;
481 const isVerified = document.getElementById('isVerified').checked;
482 const hasPayment = document.getElementById('hasPayment').checked;
483 const isAdmin = document.getElementById('isAdmin').checked;
484
485 // Different access levels based on conditions
486 const canLogin = hasAccount && isVerified;
487 const canPurchase = canLogin && hasPayment;
488 const canAccessPremium = canPurchase || isAdmin;
489 const canManageUsers = isAdmin && hasAccount;
490
491 let accessLevel, permissions = [], restrictions = [];
492
493 if (!hasAccount) {
494 accessLevel = "No Access";
495 permissions = ["View public content only"];
496 restrictions = ["Must create account", "Cannot save preferences", "Limited features"];
497 } else if (!isVerified) {
498 accessLevel = "Unverified User";
499 permissions = ["Limited account access", "View content"];
500 restrictions = ["Must verify email", "Cannot purchase", "Limited functionality"];
501 } else if (!hasPayment && !isAdmin) {
502 accessLevel = "Basic User";
503 permissions = ["Full free content", "Save preferences", "Community access"];
504 restrictions = ["Cannot purchase premium content", "Limited storage", "No priority support"];
505 } else if (canPurchase && !isAdmin) {
506 accessLevel = "Premium User";
507 permissions = ["All content access", "Premium features", "Priority support", "Extra storage"];
508 restrictions = ["Cannot manage other users", "Cannot access admin panel"];
509 } else if (isAdmin) {
510 accessLevel = "Administrator";
511 permissions = ["All user permissions", "User management", "Admin panel", "System configuration"];
512 restrictions = ["Must follow admin guidelines", "Actions are logged"];
513 }
514
515 document.getElementById('accessOutput').innerHTML = `526`;
527 }
528
529 function demonstrateLogical() {
530 const hasAccount = document.getElementById('hasAccount').checked;
531 const isVerified = document.getElementById('isVerified').checked;
532 const hasPayment = document.getElementById('hasPayment').checked;
533 const isAdmin = document.getElementById('isAdmin').checked;
534
535 document.getElementById('accessOutput').innerHTML = `552`;
553 }
554
555 // 4. SWITCH STATEMENTS - Action Processing
556 function processAction() {
557 const action = document.getElementById('actionSelect').value;
558 let result, statusCode, message;
559
560 switch (action) {
561 case 'login':
562 result = "Authenticating user credentials...";
563 statusCode = 200;
564 message = "Login successful! Welcome back!";
565 break;
566 case 'logout':
567 result = "Ending user session...";
568 statusCode = 200;
569 message = "You have been logged out successfully.";
570 break;
571 case 'register':
572 result = "Creating new user account...";
573 statusCode = 201;
574 message = "Account created! Please verify your email.";
575 break;
576 case 'forgot-password':
577 result = "Sending password reset email...";
578 statusCode = 200;
579 message = "Password reset link sent to your email.";
580 break;
581 case 'update-profile':
582 result = "Updating user profile information...";
583 statusCode = 200;
584 message = "Profile updated successfully!";
585 break;
586 case 'delete-account':
587 result = "Processing account deletion...";
588 statusCode = 200;
589 message = "Account deleted. We're sorry to see you go!";
590 break;
591 default:
592 result = "Unknown action received";
593 statusCode = 400;
594 message = "Invalid action. Please try again.";
595 break;
596 }
597
598 document.getElementById('switchOutput').innerHTML = `620`;
621 }
622
623 function getDayName() {
624 const dayNumber = parseInt(document.getElementById('dayInput').value);
625 let dayName, weekend, workday;
626
627 switch (dayNumber) {
628 case 1:
629 dayName = "Monday";
630 weekend = false;
631 workday = true;
632 break;
633 case 2:
634 dayName = "Tuesday";
635 weekend = false;
636 workday = true;
637 break;
638 case 3:
639 dayName = "Wednesday";
640 weekend = false;
641 workday = true;
642 break;
643 case 4:
644 dayName = "Thursday";
645 weekend = false;
646 workday = true;
647 break;
648 case 5:
649 dayName = "Friday";
650 weekend = false;
651 workday = true;
652 break;
653 case 6:
654 dayName = "Saturday";
655 weekend = true;
656 workday = false;
657 break;
658 case 7:
659 dayName = "Sunday";
660 weekend = true;
661 workday = false;
662 break;
663 default:
664 dayName = "Invalid Day";
665 weekend = false;
666 workday = false;
667 break;
668 }
669
670 document.getElementById('switchOutput').innerHTML = `687`;
688 }
689
690 // 5. COMPLEX CONDITIONS - E-commerce Discount System
691 function calculateDiscount() {
692 const cartTotal = parseFloat(document.getElementById('cartTotal').value) || 0;
693 const membershipType = document.getElementById('membershipType').value;
694 const isFirstTime = document.getElementById('isFirstTime').checked;
695 const hasPromoCode = document.getElementById('hasPromoCode').checked;
696 const isBirthday = document.getElementById('isBirthday').checked;
697
698 let discountPercentage = 0;
699 let discountReasons = [];
700
701 // Membership discounts
702 if (membershipType === 'bronze' && cartTotal >= 50) {
703 discountPercentage += 5;
704 discountReasons.push("Bronze member (5%)");
705 } else if (membershipType === 'silver' && cartTotal >= 50) {
706 discountPercentage += 10;
707 discountReasons.push("Silver member (10%)");
708 } else if (membershipType === 'gold' && cartTotal >= 25) {
709 discountPercentage += 15;
710 discountReasons.push("Gold member (15%)");
711 } else if (membershipType === 'platinum') {
712 discountPercentage += 20;
713 discountReasons.push("Platinum member (20%)");
714 }
715
716 // Additional discounts
717 if (isFirstTime && cartTotal >= 25) {
718 discountPercentage += 10;
719 discountReasons.push("First-time customer (10%)");
720 }
721
722 if (hasPromoCode) {
723 discountPercentage += 15;
724 discountReasons.push("Promo code applied (15%)");
725 }
726
727 if (isBirthday) {
728 discountPercentage += 10;
729 discountReasons.push("Birthday special (10%)");
730 }
731
732 // Volume discounts
733 if (cartTotal >= 100 && cartTotal < 200) {
734 discountPercentage += 5;
735 discountReasons.push("Volume discount $100+ (5%)");
736 } else if (cartTotal >= 200) {
737 discountPercentage += 10;
738 discountReasons.push("Volume discount $200+ (10%)");
739 }
740
741 // Cap maximum discount at 50%
742 if (discountPercentage > 50) {
743 discountPercentage = 50;
744 discountReasons.push("(Capped at maximum 50%)");
745 }
746
747 const discountAmount = (cartTotal * discountPercentage) / 100;
748 const finalTotal = cartTotal - discountAmount;
749
750 document.getElementById('discountOutput').innerHTML = `769`;
770 }
771
772 // 6. WEATHER ADVICE SYSTEM
773 function getWeatherAdvice() {
774 const temp = parseInt(document.getElementById('temperature').value);
775 const condition = document.getElementById('weatherCondition').value;
776 const wind = parseInt(document.getElementById('windSpeed').value);
777
778 let advice = [];
779 let activities = [];
780 let warnings = [];
781
782 // Temperature-based advice
783 if (temp < 32) {
784 advice.push("Bundle up! It's freezing outside.");
785 activities.push("Ice skating", "Hot cocoa", "Indoor activities");
786 if (temp < 10) {
787 warnings.push("Extreme cold - limit outdoor exposure");
788 }
789 } else if (temp < 50) {
790 advice.push("Wear a warm coat or jacket.");
791 activities.push("Brisk walks", "Coffee shops", "Museums");
792 } else if (temp < 70) {
793 advice.push("Light jacket or sweater recommended.");
794 activities.push("Hiking", "Sightseeing", "Outdoor dining");
795 } else if (temp < 80) {
796 advice.push("Perfect weather! Light clothing is ideal.");
797 activities.push("Parks", "Beach", "Cycling", "Picnics");
798 } else if (temp < 90) {
799 advice.push("Warm weather - stay hydrated!");
800 activities.push("Swimming", "Water sports", "Early morning activities");
801 } else {
802 advice.push("Very hot! Seek shade and stay cool.");
803 activities.push("Indoor shopping", "Air-conditioned venues", "Swimming pools");
804 if (temp > 95) {
805 warnings.push("Heat advisory - avoid prolonged sun exposure");
806 }
807 }
808
809 // Weather condition advice
810 switch (condition) {
811 case 'sunny':
812 advice.push("Don't forget sunscreen!");
813 activities.push("Beach", "Hiking", "Outdoor sports");
814 break;
815 case 'cloudy':
816 advice.push("Great day for outdoor activities without harsh sun.");
817 break;
818 case 'rainy':
819 advice.push("Bring an umbrella or raincoat!");
820 activities.push("Museums", "Shopping", "Movie theater");
821 warnings.push("Slippery roads - drive carefully");
822 break;
823 case 'snowy':
824 advice.push("Snow boots and warm clothes are essential!");
825 activities.push("Skiing", "Snowboarding", "Building snowmen");
826 warnings.push("Icy conditions - use caution when walking/driving");
827 break;
828 case 'stormy':
829 advice.push("Stay indoors! Dangerous weather conditions.");
830 activities.push("Indoor entertainment", "Reading", "Board games");
831 warnings.push("Severe weather alert - avoid outdoor activities");
832 break;
833 }
834
835 // Wind-based advice
836 if (wind > 20) {
837 advice.push("Windy conditions - secure loose items.");
838 if (wind > 30) {
839 warnings.push("High winds - be careful with umbrellas and outdoor signs");
840 }
841 }
842
843 document.getElementById('weatherOutput').innerHTML = `869`;
870 }
871
872 // INTERACTIVE CHALLENGES
873 function checkPasswordStrength() {
874 const password = document.getElementById('passwordInput').value;
875 let score = 0;
876 let feedback = [];
877 let strength;
878
879 // Length check
880 if (password.length >= 8) {
881 score += 2;
882 feedback.push("✅ Good length (8+ characters)");
883 } else if (password.length >= 6) {
884 score += 1;
885 feedback.push("⚠️ Minimum length (6+ characters)");
886 } else {
887 feedback.push("❌ Too short (needs 6+ characters)");
888 }
889
890 // Character type checks
891 if (/[a-z]/.test(password)) {
892 score += 1;
893 feedback.push("✅ Contains lowercase letters");
894 } else {
895 feedback.push("❌ Needs lowercase letters");
896 }
897
898 if (/[A-Z]/.test(password)) {
899 score += 1;
900 feedback.push("✅ Contains uppercase letters");
901 } else {
902 feedback.push("❌ Needs uppercase letters");
903 }
904
905 if (/d/.test(password)) {
906 score += 1;
907 feedback.push("✅ Contains numbers");
908 } else {
909 feedback.push("❌ Needs numbers");
910 }
911
912 if (/[!@#$%^&*(),.?":{}|<>]/.test(password)) {
913 score += 2;
914 feedback.push("✅ Contains special characters");
915 } else {
916 feedback.push("❌ Needs special characters");
917 }
918
919 // Determine strength
920 if (score >= 6) {
921 strength = "Strong";
922 } else if (score >= 4) {
923 strength = "Moderate";
924 } else if (score >= 2) {
925 strength = "Weak";
926 } else {
927 strength = "Very Weak";
928 }
929
930 document.getElementById('challengeOutput').innerHTML = `936`;
937 }
938
939 function classifyNumber() {
940 const num = parseInt(document.getElementById('numberInput').value);
941 let classifications = [];
942
943 // Basic classifications
944 if (num === 0) {
945 classifications.push("Zero");
946 } else if (num > 0) {
947 classifications.push("Positive");
948 } else {
949 classifications.push("Negative");
950 }
951
952 // Even/Odd
953 if (num % 2 === 0) {
954 classifications.push("Even");
955 } else {
956 classifications.push("Odd");
957 }
958
959 // Size classifications
960 if (Math.abs(num) < 10) {
961 classifications.push("Single digit");
962 } else if (Math.abs(num) < 100) {
963 classifications.push("Double digit");
964 } else if (Math.abs(num) < 1000) {
965 classifications.push("Triple digit");
966 } else {
967 classifications.push("Large number");
968 }
969
970 // Special numbers
971 if (num > 1) {
972 let isPrime = true;
973 for (let i = 2; i <= Math.sqrt(num); i++) {
974 if (num % i === 0) {
975 isPrime = false;
976 break;
977 }
978 }
979 if (isPrime) classifications.push("Prime number");
980 }
981
982 if (Math.sqrt(num) === Math.floor(Math.sqrt(num))) {
983 classifications.push("Perfect square");
984 }
985
986 document.getElementById('challengeOutput').innerHTML = `999`;
1000 }
1001
1002 // Initialize demo when page loads
1003 document.addEventListener('DOMContentLoaded', function() {
1004 console.log('🧠 Control Flow & Conditionals Demo Loaded!');
1005
1006 // Set up initial demo state
1007 setTimeout(() => {
1008 document.getElementById('ageOutput').innerHTML = `1012`;
1013 }, 1000);
1014 });
1015 </script>
1016</body>
1017</html>This comprehensive Control Flow & Conditionals demonstration covers all essential decision-making concepts from Lesson 4:
🎯 Complete Conditional Logic Coverage:
1. If/Else Statement Mastery:
2. Comparison Operators Implementation:
3. Logical Operators in Practice:
4. Switch Statement Mastery:
5. Complex Conditional Logic:
6. Real-World Application Examples:
7. Advanced Conditional Patterns:
8. Interactive Learning Elements:
9. Professional Best Practices:
10. Practical Problem-Solving:
This demonstration serves as both a learning tool and practical reference, showing how control flow and conditionals create intelligent, responsive applications that adapt to different scenarios and user inputs.
Excellent work mastering control flow and conditionals! You can now create programs that make intelligent decisions and respond to different scenarios. In our next lesson, we'll explore Loops & Iteration Patterns, where you'll learn how to repeat code execution, process arrays, and automate repetitive tasks efficiently. Get ready to discover the power of iteration in JavaScript programming!
Your progress is saved in this browser, on this device only.