Control Flow determines the order in which JavaScript executes code.
By default, JavaScript executes code from top to bottom.
console.log("Step 1");
console.log("Step 2");
console.log("Step 3");
Output
Step 1
Step 2
Step 3
Control Flow allows programs to:
JavaScript provides several ways to control program execution:
ifif...elseif...else if...elseswitchtry...catchtry...catch...finallythrowThe if statement executes code only when a condition is true.
if (condition) {
// code
}
let age = 20;
if (age >= 18) {
console.log("Adult");
}
Output
Adult
let age = 15;
if (age >= 18) {
console.log("Adult");
}
Output
(No Output)
Executes one block if the condition is true and another block if it is false.
if (condition) {
// true block
} else {
// false block
}
let age = 16;
if (age >= 18) {
console.log("Adult");
} else {
console.log("Minor");
}
Output
Minor
Used when there are multiple conditions.
if (condition1) {
}
else if (condition2) {
}
else {
}
let score = 75;
if (score >= 90) {
console.log("A");
}
else if (score >= 80) {
console.log("B");
}
else if (score >= 70) {
console.log("C");
}
else {
console.log("Fail");
}
Output
C
An if statement can be placed inside another if.
let age = 25;
let hasLicense = true;
if (age >= 18) {
if (hasLicense) {
console.log("Can Drive");
}
}
Output
Can Drive
Logical operators are commonly used with if statements.
&&)let age = 25;
if (age >= 18 && age <= 60) {
console.log("Working Age");
}
Both conditions must be true.
||)let role = "admin";
if (
role === "admin" ||
role === "manager"
) {
console.log("Access Granted");
}
At least one condition must be true.
!)let isLoggedIn = false;
if (!isLoggedIn) {
console.log("Login Required");
}
Output
Login Required
The switch statement compares one value against multiple possible values.
Instead of writing many if...else statements, a switch can make the code cleaner.
switch (expression) {
case value1:
break;
case value2:
break;
default:
}
let day = 2;
switch (day) {
case 1:
console.log("Sunday");
break;
case 2:
console.log("Monday");
break;
case 3:
console.log("Tuesday");
break;
default:
console.log("Invalid Day");
}
Output
Monday
The break statement stops the execution of the current case.
Without break, JavaScript continues executing the next cases.
let day = 1;
switch (day) {
case 1:
console.log("Sunday");
case 2:
console.log("Monday");
}
Output
Sunday
Monday
This behavior is called Fall Through.
The default block executes when no case matches.
let color = "blue";
switch (color) {
case "red":
console.log("Red");
break;
default:
console.log("Unknown");
}
Output
Unknown
Multiple cases can share the same block.
let role = "admin";
switch (role) {
case "admin":
case "manager":
console.log("Access Granted");
break;
}
Output
Access Granted
| if | switch |
|---|---|
| Complex Conditions | Fixed Values |
| More Flexible | More Readable |
| Range Checks | Exact Matches |
Examples
Use if
if (score > 80)
Use switch
switch (day)
An Exception is an error that occurs while a program is running.
Example
console.log(user.name);
If user does not exist, JavaScript throws a ReferenceError.
Without error handling, the program may stop executing.
Benefits:
The try...catch statement catches runtime errors.
try {
// risky code
}
catch (error) {
// handle error
}
try {
console.log(user.name);
}
catch (error) {
console.log("Error Occurred");
}
Output
Error Occurred
Instead of crashing, the error is handled safely.
The catch block receives an error object.
try {
console.log(user.name);
}
catch (error) {
console.log(error);
}
Output
ReferenceError...
try {
console.log(user.name);
}
catch (error) {
console.log(error.message);
}
Output
user is not defined
The finally block always executes, whether an error occurs or not.
try {
}
catch (error) {
}
finally {
}
try {
console.log("Start");
}
catch (error) {
console.log("Error");
}
finally {
console.log("Finished");
}
Output
Start
Finished
try {
console.log(user.name);
}
catch (error) {
console.log("Error");
}
finally {
console.log("Cleanup");
}
Output
Error
Cleanup
The finally block is commonly used for:
The throw statement creates custom errors.
throw value;
throw "Something Went Wrong";
try {
throw "Custom Error";
}
catch (error) {
console.log(error);
}
Output
Custom Error
let age = 15;
try {
if (age < 18) {
throw "Must Be 18+";
}
console.log("Allowed");
}
catch (error) {
console.log(error);
}
Output
Must Be 18+
The recommended approach is to throw an Error object.
throw new Error("Invalid Age");
Example
try {
throw new Error("Invalid Age");
}
catch (error) {
console.log(error.message);
}
Output
Invalid Age
console.log(user);
Output
ReferenceError
Variable does not exist.
null.toUpperCase();
Output
TypeError
An operation is performed on an invalid type.
if (
Output
SyntaxError
Invalid JavaScript syntax.
new Array(-1);
Output
RangeError
Invalid numeric range.
function divide(a, b) {
try {
if (b === 0) {
throw new Error(
"Cannot Divide By Zero"
);
}
return a / b;
}
catch (error) {
console.log(error.message);
}
}
Usage
divide(10, 0);
Output
Cannot Divide By Zero
let role = "admin";
try {
switch (role) {
case "admin":
console.log("Full Access");
break;
default:
throw new Error(
"Access Denied"
);
}
}
catch (error) {
console.log(error.message);
}
finally {
console.log("Process Completed");
}
Output
Full Access
Process Completed
Good
if (age === 18)
Avoid
if (age == 18)
Good
switch (status)
Good
if (
age >= 18 &&
age <= 60
)
Good
throw new Error("Invalid Input");
Avoid
throw "Invalid Input";
Use try...catch when working with:
| Concept | Purpose |
|---|---|
if |
Execute code conditionally |
if...else |
Two possible paths |
else if |
Multiple conditions |
switch |
Multiple fixed values |
break |
Exit a switch case |
default |
Fallback case |
try |
Execute risky code |
catch |
Handle errors |
finally |
Always executes |
throw |
Create custom errors |
Error |
Built-in error object |
Control Flow allows JavaScript programs to make decisions and handle errors safely.
Decision Making
↓
if / else
switch
Error Handling
↓
try
catch
finally
throw
A common pattern in modern JavaScript is:
try {
if (!user) {
throw new Error(
"User Not Found"
);
}
}
catch (error) {
console.log(error.message);
}
finally {
console.log("Done");
}
Understanding control flow is essential because every real-world application uses conditions, permissions, form validation, API responses, and error handling to create reliable and user-friendly software.