Control flow is the order in which the computer executes statements in a script.
if...else StatementThe most common way to branch logic.
JavaScript
let age = 18;
if (age >= 18) {
console.log("You can vote.");
} else if (age >= 16) {
console.log("You can drive, but not vote.");
} else {
console.log("Too young.");
}
Ideal for simple assignments based on a condition.
Syntax:
condition ? value_if_true : value_if_false;
JavaScript
let access = age >= 18 ? "Granted" : "Denied";
switch StatementBest used when you have many fixed options for a single variable. It is more readable than 10 if else blocks.
JavaScript
let day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the week!");
break; // Crucial: Prevents "falling through" to the next case
case "Friday":
console.log("Weekend is near.");
break;
default:
console.log("Just a normal day.");
}
JavaScript allows you to combine conditions using && (AND), || (OR), and ! (NOT).
JavaScript engines stop evaluating as soon as the result is certain.
&& (AND): Returns the first falsy value, or the last value if all are truthy.|| (OR): Returns the first truthy value.JavaScript
// Example: Setting a default value
let name = "";
let displayName = name || "Anonymous"; // "Anonymous" because empty string is falsy
// Example: Guarding against errors
let user = null;
user && user.getName(); // Doesn't crash! It stops at 'user' because it's null.
??)Introduced in ES2020, this is smarter than ||. It only triggers for null or undefined. It ignores 0 or "".
JavaScript
let speed = 0;
let val1 = speed || 30; // 30 (because 0 is falsy)
let val2 = speed ?? 30; // 0 (because 0 is NOT null or undefined)
try...catch)No matter how good a coder you are, errors will happen (e.g., a network failure). To prevent the entire script from stopping, we use try...catch.
JavaScript
try {
// Code that might throw an error
let data = JSON.parse("invalid-json");
} catch (error) {
// This runs only if an error occurs
console.error("Oops! Something went wrong:", error.message);
} finally {
// This runs NO MATTER WHAT (Cleanup code)
console.log("Closing connection...");
}
You can force an error to happen using the throw keyword.
JavaScript
function checkAge(age) {
if (age < 0) throw new Error("Age cannot be negative!");
return true;
}
Loops allow you to repeat a block of code.
| Loop Type | Best Use Case |
for | When you know exactly how many times to loop. |
while | When you loop until a specific condition changes. |
do...while | Same as while, but guaranteed to run at least once. |
for...of | Best for iterating over Arrays or Strings. |
for...in | Best for iterating over Object properties. |
Break vs. Continue:
break: Exits the loop entirely.continue: Skips the current iteration and jumps to the next one.JavaScript
const users = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: null },
{ name: "Charlie", age: 17 }
];
for (let user of users) {
try {
let userAge = user.age ?? "Unknown"; // Nullish coalescing
if (typeof userAge !== "number") {
throw new Error(`Invalid age for ${user.name}`);
}
console.log(`${user.name} is ${userAge >= 18 ? "an Adult" : "a Minor"}`);
} catch (err) {
console.warn(err.message);
}
}
Control flow determines the order in which statements are executed in a program.
By default, programs execute top to bottom, but control flow statements allow:
Example:
read input
process data
print output
Used for simple, linear tasks.
if StatementExecutes code when a condition is true.
Example:
if (marks > 40)
print("Pass")
if-elseChooses between two paths.
Example:
if (age >= 18)
print("Eligible")
else
print("Not Eligible")
else-if LadderUsed for multiple conditions.
Example:
if (score >= 90)
grade = "A"
else if (score >= 75)
grade = "B"
else
grade = "C"
ifAn if inside another if.
Used for complex decision logic.
switch-caseExecutes code based on a variable’s value.
Example:
switch(day) {
case 1: print("Monday")
case 2: print("Tuesday")
default: print("Invalid")
}
| Feature | if-else | switch |
|---|---|---|
| Conditions | Boolean expressions | Fixed values |
| Readability | Medium | High |
| Performance | Slower for many cases | Faster |
| Flexibility | High | Limited |
Loops execute a block of code repeatedly.
for LoopUsed when number of iterations is known.
Example:
for (i = 1; i <= 5; i++)
print(i)
while LoopExecutes while condition is true.
Example:
while (balance > 0)
deduct()
do-while LoopExecutes at least once.
Example:
do {
readInput()
} while (input != 0)
Loop inside another loop.
Used for:
breakTerminates loop immediately.
continueSkips current iteration.
returnExits a function and returns a value.
An error is a problem that disrupts normal program execution.
Examples:
An exception is a runtime error that can be caught and handled gracefully.
tryCode that may cause an error.
catchHandles the error.
finallyExecutes regardless of error occurrence.
Example:
try {
divide(a, b)
}
catch (error) {
print("Error occurred")
}
finally {
closeResources()
}
Handles different exception types separately.
throwUsed to explicitly raise an exception.
Example:
if (age < 18)
throw Error("Invalid Age")
(Important for C)
errno