Course

Web Development
  • 1.1 Introduction to the Web
  • 2.1 HTML Basics
  • 2.2 Text & Content
  • 2.3 Layout & Grouping
  • 2.4 Lists & Tables
  • 2.5 Media & Embedding
  • 2.6 Forms
  • 2.7 Semantic HTML
  • 2.8 Accessibility & SEO
  • 3.1 CSS Introduction
  • 3.2 CSS Syntax
  • 3.3 CSS Selectors
  • 3.4 Typography
  • 3.5 Colors & Backgrounds
  • 3.6 Text Styling
  • 3.7 Box Model
  • 3.8 Units
  • 3.9 Display & Positioning
  • 3.10 Layout Systems
  • 3.11 Responsive Design
  • 3.12 Animations
  • 3.13 Modern CSS
  • 3.14 Performance & Accessibility
  • 3.15 Tailwind CSS Basics
  • 4.1 Introduction to JavaScript
  • 4.2 Variables & Scope
  • 4.3 Data Types
  • 4.4 Type Conversion
  • 4.5 Operators
  • 4.6 Control Flow
  • 4.7 Loops
  • 4.8 Functions
  • 4.9 Advanced Functions
  • 4.10 Objects & Arrays
  • 4.11 The this Keyword

4.6 Control Flow

Updated Jul 23, 2026

4.6 Control Flow

Updated Jul 23, 2026

4.6 Control Flow

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:

  • Make Decisions
  • Execute Different Code Paths
  • Handle Errors
  • Control Program Behavior

Types of Control Flow

JavaScript provides several ways to control program execution:

  1. if
  2. if...else
  3. if...else if...else
  4. switch
  5. Exception Handling
  6. try...catch
  7. try...catch...finally
  8. throw

if Statement

The if statement executes code only when a condition is true.

Syntax

if (condition) {

    // code

}

Example

let age = 20;

if (age >= 18) {

    console.log("Adult");

}

Output

Adult

Condition is False

let age = 15;

if (age >= 18) {

    console.log("Adult");

}

Output

(No Output)

if...else Statement

Executes one block if the condition is true and another block if it is false.

Syntax

if (condition) {

    // true block

} else {

    // false block

}

Example

let age = 16;

if (age >= 18) {

    console.log("Adult");

} else {

    console.log("Minor");

}

Output

Minor

if...else if...else Statement

Used when there are multiple conditions.

Syntax

if (condition1) {

}
else if (condition2) {

}
else {

}

Example

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

Nested if Statements

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 in Conditions

Logical operators are commonly used with if statements.


AND (&&)

let age = 25;

if (age >= 18 && age <= 60) {

    console.log("Working Age");

}

Both conditions must be true.


OR (||)

let role = "admin";

if (
    role === "admin" ||
    role === "manager"
) {

    console.log("Access Granted");

}

At least one condition must be true.


NOT (!)

let isLoggedIn = false;

if (!isLoggedIn) {

    console.log("Login Required");

}

Output

Login Required

switch Statement

The switch statement compares one value against multiple possible values.

Instead of writing many if...else statements, a switch can make the code cleaner.


Syntax

switch (expression) {

    case value1:

        break;

    case value2:

        break;

    default:

}

Example

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

Importance of break

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.


default Case

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

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 vs switch

if switch
Complex Conditions Fixed Values
More Flexible More Readable
Range Checks Exact Matches

Examples

Use if

if (score > 80)

Use switch

switch (day)

Exception Handling

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.


Why Exception Handling?

Benefits:

  • Prevent Application Crashes
  • Handle Errors Gracefully
  • Improve User Experience
  • Make Programs More Reliable

try...catch

The try...catch statement catches runtime errors.

Syntax

try {

    // risky code

}
catch (error) {

    // handle error

}

Example

try {

    console.log(user.name);

}
catch (error) {

    console.log("Error Occurred");

}

Output

Error Occurred

Instead of crashing, the error is handled safely.


Error Object

The catch block receives an error object.

try {

    console.log(user.name);

}
catch (error) {

    console.log(error);

}

Output

ReferenceError...

Error Message

try {

    console.log(user.name);

}
catch (error) {

    console.log(error.message);

}

Output

user is not defined

try...catch...finally

The finally block always executes, whether an error occurs or not.

Syntax

try {

}
catch (error) {

}
finally {

}

Example

try {

    console.log("Start");

}
catch (error) {

    console.log("Error");

}
finally {

    console.log("Finished");

}

Output

Start
Finished

Example with Error

try {

    console.log(user.name);

}
catch (error) {

    console.log("Error");

}
finally {

    console.log("Cleanup");

}

Output

Error
Cleanup

Why Use finally?

The finally block is commonly used for:

  • Closing Files
  • Closing Database Connections
  • Cleanup Tasks
  • Releasing Resources

throw Statement

The throw statement creates custom errors.

Syntax

throw value;

Example

throw "Something Went Wrong";

Example with try...catch

try {

    throw "Custom Error";

}
catch (error) {

    console.log(error);

}

Output

Custom Error

Validation Example

let age = 15;

try {

    if (age < 18) {

        throw "Must Be 18+";

    }

    console.log("Allowed");

}
catch (error) {

    console.log(error);

}

Output

Must Be 18+

Throwing Error Objects

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

Common Error Types

ReferenceError

console.log(user);

Output

ReferenceError

Variable does not exist.


TypeError

null.toUpperCase();

Output

TypeError

An operation is performed on an invalid type.


SyntaxError

if (

Output

SyntaxError

Invalid JavaScript syntax.


RangeError

new Array(-1);

Output

RangeError

Invalid numeric range.


Real-World Example

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

Complete Example

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

Best Practices

Use Strict Comparison

Good

if (age === 18)

Avoid

if (age == 18)

Use switch for Fixed Values

Good

switch (status)

Use if for Complex Conditions

Good

if (
    age >= 18 &&
    age <= 60
)

Throw Error Objects

Good

throw new Error("Invalid Input");

Avoid

throw "Invalid Input";

Handle Expected Errors

Use try...catch when working with:

  • APIs
  • User Input
  • Files
  • Databases

Summary

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

Key Takeaway

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.

4.5 Operators4.7 Loops