Log In

Don't have an account? Sign up now

Lost Password?

Sign Up

Prev Next

Module 4: Control Flow & Error Handling

1. Decision Making (Conditionals)

Control flow is the order in which the computer executes statements in a script.

A. The if...else Statement

The 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.");
}

B. Ternary Operator (The Shortcut)

Ideal for simple assignments based on a condition.

Syntax: condition ? value_if_true : value_if_false;

JavaScript

let access = age >= 18 ? "Granted" : "Denied";

C. The switch Statement

Best 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.");
}

2. Logical Operators & Short-Circuiting

JavaScript allows you to combine conditions using && (AND), || (OR), and ! (NOT).

Short-Circuit Evaluation

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.

3. The Nullish Coalescing Operator (??)

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)

4. Error Handling (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.

The Structure:

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...");
}

Throwing Custom Errors

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;
}

5. Loops: The Iteration Tools

Loops allow you to repeat a block of code.

Loop TypeBest Use Case
forWhen you know exactly how many times to loop.
whileWhen you loop until a specific condition changes.
do...whileSame as while, but guaranteed to run at least once.
for...ofBest for iterating over Arrays or Strings.
for...inBest for iterating over Object properties.

Break vs. Continue:

  • break: Exits the loop entirely.
  • continue: Skips the current iteration and jumps to the next one.

💻 Technical Code Example: The Robust Logic

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);
    }
}

In Simple Words

1. Introduction to Control Flow

What is Control Flow?

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:

  • Decision making
  • Repetition
  • Branching
  • Exception handling

Why Control Flow is Important

  • Builds program logic
  • Enables dynamic behavior
  • Handles real-world conditions
  • Prevents crashes and incorrect output

2. Types of Control Flow Statements

Main Categories

  1. Sequential Control
  2. Decision-Making (Conditional) Statements
  3. Looping (Iteration) Statements
  4. Jump Statements
  5. Error & Exception Handling

3. Sequential Control

  • Statements execute in the order written
  • No condition or branching

Example:

read input
process data
print output

Used for simple, linear tasks.


4. Decision-Making Statements

1. if Statement

Executes code when a condition is true.

Example:

if (marks > 40)
   print("Pass")

2. if-else

Chooses between two paths.

Example:

if (age >= 18)
   print("Eligible")
else
   print("Not Eligible")

3. else-if Ladder

Used for multiple conditions.

Example:

if (score >= 90)
   grade = "A"
else if (score >= 75)
   grade = "B"
else
   grade = "C"

4. Nested if

An if inside another if.

Used for complex decision logic.


5. switch-case

Executes code based on a variable’s value.

Example:

switch(day) {
   case 1: print("Monday")
   case 2: print("Tuesday")
   default: print("Invalid")
}

5. Comparison: if-else vs switch

Featureif-elseswitch
ConditionsBoolean expressionsFixed values
ReadabilityMediumHigh
PerformanceSlower for many casesFaster
FlexibilityHighLimited

6. Looping (Iteration) Statements

Loops execute a block of code repeatedly.


1. for Loop

Used when number of iterations is known.

Example:

for (i = 1; i <= 5; i++)
   print(i)

2. while Loop

Executes while condition is true.

Example:

while (balance > 0)
   deduct()

3. do-while Loop

Executes at least once.

Example:

do {
   readInput()
} while (input != 0)

4. Nested Loops

Loop inside another loop.

Used for:

  • Patterns
  • Matrices
  • Tables

7. Loop Control Statements

break

Terminates loop immediately.


continue

Skips current iteration.


return

Exits a function and returns a value.


8. Common Loop Errors

  • Infinite loops
  • Off-by-one errors
  • Incorrect condition checks
  • Missing increment/decrement

9. Introduction to Error Handling

What is an Error?

An error is a problem that disrupts normal program execution.

Examples:

  • Division by zero
  • File not found
  • Invalid input
  • Null reference

10. Types of Errors

1. Syntax Errors

  • Violates language rules
  • Detected at compile time

2. Runtime Errors

  • Occur during execution
  • Causes program crash

3. Logical Errors

  • Program runs but gives wrong output
  • Hardest to detect

11. Exception Handling

What is an Exception?

An exception is a runtime error that can be caught and handled gracefully.


Why Exception Handling?

  • Prevents program crash
  • Improves reliability
  • Provides meaningful error messages

12. Try-Catch-Finally Mechanism

try

Code that may cause an error.


catch

Handles the error.


finally

Executes regardless of error occurrence.

Example:

try {
   divide(a, b)
}
catch (error) {
   print("Error occurred")
}
finally {
   closeResources()
}

13. Multiple Catch Blocks

Handles different exception types separately.


14. Throwing Exceptions

throw

Used to explicitly raise an exception.

Example:

if (age < 18)
   throw Error("Invalid Age")

15. Custom Exceptions

  • User-defined exceptions
  • Improve error clarity
  • Useful in large applications

16. Error Handling Without Exceptions

(Important for C)

  • Error codes
  • Return values
  • errno

Leave a Comment

    🚀 Join Common Jobs Pro — Referrals & Profile Visibility Join Now ×
    🔥