JavaScript 11 🧬 Control flow and Conditional execution
11. Control Flow and Conditional Execution
Control flow in JavaScript refers to the order in which code is executed, and how the execution path can be altered based on certain conditions or statements.
A Quick Look at the Examples
// Simple if
let age = 20;
if (age >= 18) {
console.log("You are an adult.");
}
// if...else
let temperature = 30;
if (temperature > 25) {
console.log("It's hot.");
} else {
console.log("It's not so hot.");
}
// if...else if...else
let score = 85;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B");
} else if (score >= 70) {
console.log("Grade: C");
} else {
console.log("Grade: F");
}
a. Control Flow
Control flow in JavaScript refers to the order in which code is executed and how the execution path can be altered based on certain conditions or statements.
Fundamental Control Structures
| Structure | Description |
|---|---|
| Sequential Execution | Code executes line by line, from top to bottom |
| Conditional Statements | Execute different blocks based on conditions |
| Looping Statements | Execute a block of code repeatedly |
| Break / Continue / Return | Alter the flow of loops and functions |
Sequential Execution
By default, code runs line by line from top to bottom:
console.log("First"); // Runs first
console.log("Second"); // Runs second
console.log("Third"); // Runs third
Conditional Execution
Changes the flow based on conditions:
let age = 20;
if (age >= 18) {
console.log("Adult"); // Runs only if condition is true
}
Looping
Repeats code multiple times:
for (let i = 0; i < 3; i++) {
console.log(i); // Runs 3 times: 0, 1, 2
}
b. Conditional Execution
Conditional execution statements are used to execute different blocks of code based on specific conditions. These statements help you control the flow of your program based on whether a certain condition is true or false.
Primary Conditional Statements
| Statement | Description |
|---|---|
if | Executes code if a condition is true |
else | Alternative block when if condition is false |
else if | Tests multiple conditions sequentially |
switch | Evaluates an expression and matches cases |
c. if, else, and else if Statements
1. The if Statement
Executes a block of code if a specified condition is true.
if (condition) {
// Code to be executed if condition is true
}
Example:
let age = 20;
if (age >= 18) {
console.log("You are an adult."); // Runs because 20 >= 18
}
Key Points:
- The condition is evaluated to a boolean (
trueorfalse) - If
true, the code block runs - If
false, the code block is skipped
2. The else Statement
Provides an alternative block of code when the if condition is false.
if (condition) {
// Code if condition is true
} else {
// Code if condition is false
}
Example:
let temperature = 30;
if (temperature > 25) {
console.log("It's hot."); // Runs because 30 > 25
} else {
console.log("It's not so hot."); // Skipped
}
3. The else if Statement
Allows for multiple conditional checks. Tests several conditions and executes the block associated with the first condition that evaluates to true.
if (condition1) {
// Code if condition1 is true
} else if (condition2) {
// Code if condition2 is true
} else if (condition3) {
// Code if condition3 is true
} else {
// Code if none of the above are true
}
Example:
let score = 85;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B"); // Runs because 85 >= 80
} else if (score >= 70) {
console.log("Grade: C");
} else {
console.log("Grade: F");
}
How it works:
- Check
score >= 90→false - Check
score >= 80→true→ Run this block, skip the rest - Remaining conditions are not evaluated
Key Points:
- Conditions are checked in order from top to bottom
- Only the first matching block runs
elseis optional — if no condition matches and there’s noelse, nothing runs
4. The switch Statement
Evaluates an expression and executes code blocks based on its value.
switch (expression) {
case value1:
// Code if expression === value1
break;
case value2:
// Code if expression === value2
break;
default:
// Code if no case matches
}
Example:
let day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the work week");
break;
case "Friday":
console.log("Almost the weekend!");
break;
case "Saturday":
case "Sunday":
console.log("Weekend!");
break;
default:
console.log("Midweek");
}
Key Points:
- Uses strict equality (
===) for comparison breakprevents fall-through to the next casedefaultis optional (likeelse)- Multiple cases can share the same block (see Saturday/Sunday)
Complete Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Control Flow and Conditional Execution</title>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
background: #f8f9fa;
color: #333;
line-height: 1.6;
}
h1 { color: #007bff; border-bottom: 3px solid #007bff; padding-bottom: 10px; }
h2 { color: #28a745; border-left: 4px solid #28a745; padding-left: 15px; margin-top: 30px; }
.demo-box {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
margin: 15px 0;
}
pre {
background: #1e1e1e;
color: #d4d4d4;
padding: 15px;
border-radius: 8px;
overflow-x: auto;
font-family: 'Courier New', monospace;
font-size: 0.9rem;
line-height: 1.8;
}
.keyword { color: #569cd6; }
.string { color: #ce9178; }
.number { color: #b5cea8; }
.function { color: #dcdcaa; }
.comment { color: #6a9955; }
.boolean { color: #569cd6; }
#output {
background: #e9ecef;
padding: 15px;
border-radius: 8px;
margin-top: 15px;
min-height: 40px;
font-family: 'Courier New', monospace;
font-size: 0.85rem;
border-left: 4px solid #007bff;
white-space: pre-wrap;
}
.input-group {
margin: 10px 0;
}
.input-group label {
display: inline-block;
min-width: 120px;
font-weight: bold;
}
.input-group input, .input-group select {
padding: 8px 12px;
border: 2px solid #ddd;
border-radius: 6px;
font-size: 1em;
width: 200px;
}
.input-group input:focus, .input-group select:focus {
outline: none;
border-color: #007bff;
}
.btn {
padding: 10px 20px;
background: #007bff;
color: white;
border: none;
border-radius: 6px;
font-size: 1em;
font-weight: bold;
cursor: pointer;
margin: 5px;
transition: all 0.3s;
}
.btn:hover {
background: #0056b3;
transform: translateY(-2px);
}
</style>
</head>
<body>
<h1>Control Flow and Conditional Execution</h1>
<div class="demo-box">
<h2>1. The if Statement</h2>
<pre>
<span class="keyword">let</span> age = <span class="number">20</span>;
<span class="keyword">if</span> (age >= <span class="number">18</span>) {
console.log(<span class="string">"You are an adult."</span>);
}
</pre>
</div>
<div class="demo-box">
<h2>2. if...else Statement</h2>
<pre>
<span class="keyword">let</span> temperature = <span class="number">30</span>;
<span class="keyword">if</span> (temperature > <span class="number">25</span>) {
console.log(<span class="string">"It's hot."</span>);
} <span class="keyword">else</span> {
console.log(<span class="string">"It's not so hot."</span>);
}
</pre>
</div>
<div class="demo-box">
<h2>3. if...else if...else Statement</h2>
<pre>
<span class="keyword">let</span> score = <span class="number">85</span>;
<span class="keyword">if</span> (score >= <span class="number">90</span>) {
console.log(<span class="string">"Grade: A"</span>);
} <span class="keyword">else if</span> (score >= <span class="number">80</span>) {
console.log(<span class="string">"Grade: B"</span>);
} <span class="keyword">else if</span> (score >= <span class="number">70</span>) {
console.log(<span class="string">"Grade: C"</span>);
} <span class="keyword">else</span> {
console.log(<span class="string">"Grade: F"</span>);
}
</pre>
</div>
<div class="demo-box">
<h2>4. Interactive: Grade Calculator</h2>
<div class="input-group">
<label for="scoreInput">Enter a score:</label>
<input type="number" id="scoreInput" min="0" max="100" value="85">
</div>
<button class="btn" onclick="checkGrade()">Check Grade</button>
<div id="gradeOutput"></div>
</div>
<div class="demo-box">
<h2>5. Interactive: Age Check</h2>
<div class="input-group">
<label for="ageInput">Enter your age:</label>
<input type="number" id="ageInput" min="0" max="150" value="20">
</div>
<button class="btn" onclick="checkAge()">Check Age</button>
<div id="ageOutput"></div>
</div>
<div class="demo-box">
<h2>6. Interactive: Day of Week (switch)</h2>
<div class="input-group">
<label for="dayInput">Select a day:</label>
<select id="dayInput">
<option value="Monday">Monday</option>
<option value="Tuesday">Tuesday</option>
<option value="Wednesday">Wednesday</option>
<option value="Thursday">Thursday</option>
<option value="Friday">Friday</option>
<option value="Saturday">Saturday</option>
<option value="Sunday">Sunday</option>
</select>
</div>
<button class="btn" onclick="checkDay()">Check Day</button>
<div id="dayOutput"></div>
</div>
<div class="demo-box">
<h2>7. Live Output — All Examples</h2>
<div id="output">Loading...</div>
</div>
<script>
// ============================================
// Control Flow and Conditional Execution — Live Demo
// ============================================
let results = [];
// 1. if statement
let age = 20;
results.push('📌 if Statement:\n');
if (age >= 18) {
results.push(' age = 20 → "You are an adult." ✅');
} else {
results.push(' age = 20 → "You are a minor."');
}
results.push('');
// 2. if...else
let temperature = 30;
results.push('📌 if...else Statement:\n');
if (temperature > 25) {
results.push(' temperature = 30 → "It\'s hot." ✅');
} else {
results.push(' temperature = 30 → "It\'s not so hot."');
}
results.push('');
// 3. if...else if...else
let score = 85;
results.push('📌 if...else if...else Statement:\n');
if (score >= 90) {
results.push(' score = 85 → "Grade: A"');
} else if (score >= 80) {
results.push(' score = 85 → "Grade: B" ✅');
} else if (score >= 70) {
results.push(' score = 85 → "Grade: C"');
} else {
results.push(' score = 85 → "Grade: F"');
}
results.push('');
// 4. Grade comparison table
results.push('📌 Grade Comparison:\n');
const testScores = [95, 85, 75, 65];
testScores.forEach(s => {
let grade;
if (s >= 90) grade = "A";
else if (s >= 80) grade = "B";
else if (s >= 70) grade = "C";
else grade = "F";
results.push(' Score ' + s + ' → Grade ' + grade);
});
results.push('');
// 5. switch statement
results.push('📌 switch Statement:\n');
const days = ["Monday", "Wednesday", "Friday", "Saturday", "Sunday"];
days.forEach(day => {
let message;
switch (day) {
case "Monday":
message = "Start of the work week";
break;
case "Friday":
message = "Almost the weekend!";
break;
case "Saturday":
case "Sunday":
message = "Weekend!";
break;
default:
message = "Midweek";
}
results.push(' ' + day + ' → ' + message);
});
results.push('');
// 6. Truthy/Falsy in conditions
results.push('📌 Truthy vs Falsy in Conditions:\n');
const testValues = [0, 1, "", "hello", null, undefined, [], {}];
testValues.forEach(v => {
const result = v ? "truthy" : "falsy";
const display = JSON.stringify(v);
results.push(' ' + display + ' → ' + result);
});
document.getElementById('output').textContent = results.join('\n');
// ============================================
// Interactive Functions
// ============================================
function checkGrade() {
const score = Number(document.getElementById('scoreInput').value);
const output = document.getElementById('gradeOutput');
let grade;
if (score >= 90) grade = "A";
else if (score >= 80) grade = "B";
else if (score >= 70) grade = "C";
else if (score >= 60) grade = "D";
else grade = "F";
output.innerHTML = `<p>Score: <strong>${score}</strong> → Grade: <strong>${grade}</strong></p>`;
output.style.color = score >= 70 ? '#28a745' : '#dc3545';
}
function checkAge() {
const age = Number(document.getElementById('ageInput').value);
const output = document.getElementById('ageOutput');
let message;
if (age < 0) {
message = "Invalid age";
} else if (age < 13) {
message = "Child";
} else if (age < 18) {
message = "Teenager";
} else if (age < 65) {
message = "Adult";
} else {
message = "Senior";
}
output.innerHTML = `<p>Age: <strong>${age}</strong> → <strong>${message}</strong></p>`;
}
function checkDay() {
const day = document.getElementById('dayInput').value;
const output = document.getElementById('dayOutput');
let message;
switch (day) {
case "Monday":
message = "Start of the work week 💼";
break;
case "Tuesday":
case "Wednesday":
case "Thursday":
message = "Midweek — keep going! 💪";
break;
case "Friday":
message = "Almost the weekend! 🎉";
break;
case "Saturday":
case "Sunday":
message = "Weekend! Relax! 🌴";
break;
default:
message = "Unknown day";
}
output.innerHTML = `<p><strong>${day}</strong> → ${message}</p>`;
}
// Run initial checks
checkGrade();
checkAge();
checkDay();
</script>
</body>
</html>
Quick Reference
Conditional Statements
| Statement | Syntax | Description |
|---|---|---|
if | if (condition) { } | Runs if condition is true |
else | else { } | Runs if if is false |
else if | else if (condition) { } | Tests multiple conditions |
switch | switch (expr) { case x: } | Matches expression to cases |
if…else if…else Template
if (condition1) {
// Code if condition1 is true
} else if (condition2) {
// Code if condition2 is true
} else if (condition3) {
// Code if condition3 is true
} else {
// Code if none are true
}
switch Template
switch (expression) {
case value1:
// Code
break;
case value2:
// Code
break;
default:
// Code if no case matches
}
Truthy vs Falsy
Falsy (→ false) | Truthy (→ true) |
|---|---|
false | Everything else |
0, -0 | "0", "false" |
"" (empty string) | [], {} |
null | function() {} |
undefined | — |
NaN | — |
Comparison Operators
| Operator | Description | Example |
|---|---|---|
=== | Strict equality | 5 === 5 → true |
!== | Strict inequality | 5 !== "5" → true |
> | Greater than | 10 > 5 → true |
< | Less than | 10 < 5 → false |
>= | Greater or equal | 10 >= 10 → true |
<= | Less or equal | 10 <= 5 → false |
Best Practices
✅ Do This:
// Use strict equality
if (value === 42) { }
// Use early returns for guard clauses
function checkAge(age) {
if (age < 0) return "Invalid";
if (age < 18) return "Minor";
return "Adult";
}
// Use switch for multiple exact matches
switch (day) {
case "Monday": /* ... */ break;
case "Friday": /* ... */ break;
default: /* ... */
}
// Use truthy/falsy checks wisely
if (array.length) { } // Empty array → 0 → false
if (user) { } // null/undefined → false
// Add braces for clarity
if (condition) {
doSomething();
}
❌ Don’t Do This:
// Don't use loose equality
if (value == 42) { } // Coerces types — surprising!
// Don't forget break in switch
switch (day) {
case "Monday":
console.log("Monday");
// Missing break — falls through!
case "Tuesday":
console.log("Tuesday");
}
// Don't use nested ternaries for complex logic
// (Hard to read)
const grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "F";
// Don't use if without braces
if (condition)
doSomething(); // OK, but risky when adding lines
// Don't compare floating-point numbers with ===
if (0.1 + 0.2 === 0.3) { } // false!
Common Pitfalls
| Pitfall | Problem | Solution |
|---|---|---|
== vs === | Type coercion | Use === |
Missing break in switch | Fall-through | Always add break |
Forgetting {} | Scope issues | Always use braces |
Assignment in if | if (x = 5) assigns, not compares | Use === or == |
| Truthy/falsy confusion | "0" is truthy | Check explicitly |
| Floating-point equality | 0.1 + 0.2 !== 0.3 | Compare with tolerance |
Pro Tip: Use strict equality (===) to avoid surprising type coercion. Use if...else if...else for range checks (like grades) and switch for exact value matches (like days of the week). Always add break in switch cases to prevent fall-through — unless you intentionally want multiple cases to share code. And remember: if (value) uses truthy/falsy — "0", [], and {} are all truthy!
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!