Module 2: Control Flow & Logic

Master control flow, loops, conditional statements, and error handling in JavaScript.

Back to Course|2.5 hours|Beginner

Control Flow & Logic

Master control flow, loops, conditional statements, and error handling in JavaScript.

Progress: 0/4 topics completed0%

Select Topics Overview

JavaScript If Else & Conditional Logic

Learn conditional statements and decision-making logic in JavaScript with modern patterns and best practices

Content by: Ronak Gajera

React.js Developer

Connect

Conditional Statements Overview

Conditional statements allow your program to make decisions and execute different code blocks based on whether certain conditions are true or false. JavaScript provides several ways to implement conditional logic.

If Statement Types

  • if: Executes code block if condition is true
  • if...else: Executes one block if true, another if false
  • if...else if...else: Multiple conditions with fallback
  • Nested if: If statements inside other if statements
  • Ternary operator: Shorthand conditional expression

Basic If Statements

Code Example
// Basic if statement
let age = 18;
if (age >= 18) {
    console.log("You are an adult");
}

// If...else statement
if (age >= 18) {
    console.log("You can vote");
} else {
    console.log("You cannot vote yet");
}

// If...else if...else chain
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 if (score >= 60) {
    console.log("Grade: D");
} else {
    console.log("Grade: F");
}

// Nested if statements
let isLoggedIn = true;
let hasPermission = false;

if (isLoggedIn) {
    if (hasPermission) {
        console.log("Access granted");
    } else {
        console.log("Access denied - insufficient permissions");
    }
} else {
    console.log("Please log in first");
}

// Ternary operator (shorthand)
let status = age >= 18 ? "adult" : "minor";
let message = `You are an ${status}`;

// Multiple conditions with logical operators
let isStudent = true;
let hasDiscount = false;
let age2 = 25;

if (isStudent && age2 < 30) {
    hasDiscount = true;
    console.log("Student discount applied");
} else if (age2 >= 65) {
    hasDiscount = true;
    console.log("Senior discount applied");
} else {
    console.log("No discount available");
}
Swipe to see more code

Modern Conditional Patterns

Code Example
// Modern conditional patterns (2025)
// Optional chaining with conditionals
let user = {
    profile: {
        settings: {
            notifications: true
        }
    }
};

if (user?.profile?.settings?.notifications) {
    console.log("Notifications are enabled");
} else {
    console.log("Notifications are disabled or not configured");
}

// Nullish coalescing with conditionals
let theme = user?.profile?.settings?.theme ?? 'light';
console.log(`Current theme: ${theme}`);

// Short-circuit evaluation
let isAdmin = user?.role === 'admin';
let canEdit = isAdmin || user?.permissions?.includes('edit');

if (canEdit) {
    console.log("User can edit content");
}

// Conditional object properties
let config = {
    apiUrl: 'https://api.example.com',
    timeout: 5000,
    ...(isAdmin && { debugMode: true }),
    ...(user?.preferences?.theme && { theme: user.preferences.theme })
};

// Conditional function calls
let logger = {
    info: (msg) => console.log(`[INFO] ${msg}`),
    error: (msg) => console.error(`[ERROR] ${msg}`),
    debug: (msg) => console.debug(`[DEBUG] ${msg}`)
};

let logLevel = 'info';
let message = 'User logged in';

if (logLevel === 'debug') {
    logger.debug(message);
} else if (logLevel === 'error') {
    logger.error(message);
} else {
    logger.info(message);
}

// Switch-like pattern with objects
const actions = {
    'create': () => console.log('Creating...'),
    'read': () => console.log('Reading...'),
    'update': () => console.log('Updating...'),
    'delete': () => console.log('Deleting...')
};

let action = 'create';
if (actions[action]) {
    actions[action]();
} else {
    console.log('Invalid action');
}
Swipe to see more code

Practice Exercise: Conditional Logic

Code Example
// Exercise: Build a Grade Calculator
function calculateGrade(score) {
    if (score >= 90) {
        return 'A';
    } else if (score >= 80) {
        return 'B';
    } else if (score >= 70) {
        return 'C';
    } else if (score >= 60) {
        return 'D';
    } else {
        return 'F';
    }
}

// Exercise: Build a User Access Control System
function checkAccess(user, resource) {
    // Check if user exists and is active
    if (!user || !user.isActive) {
        return { allowed: false, reason: 'User not found or inactive' };
    }
    
    // Check if user has required permissions
    if (!user.permissions || !user.permissions.includes(resource)) {
        return { allowed: false, reason: 'Insufficient permissions' };
    }
    
    // Check if user is admin (bypass all restrictions)
    if (user.role === 'admin') {
        return { allowed: true, reason: 'Admin access' };
    }
    
    // Check time-based restrictions
    const currentHour = new Date().getHours();
    if (currentHour < 6 || currentHour > 22) {
        return { allowed: false, reason: 'Access restricted outside business hours' };
    }
    
    return { allowed: true, reason: 'Access granted' };
}

// Test the functions
console.log(calculateGrade(95)); // 'A'
console.log(calculateGrade(85)); // 'B'
console.log(calculateGrade(75)); // 'C'
console.log(calculateGrade(55)); // 'F'

const user1 = {
    id: 1,
    name: 'John',
    isActive: true,
    role: 'user',
    permissions: ['read', 'write']
};

const user2 = {
    id: 2,
    name: 'Admin',
    isActive: true,
    role: 'admin',
    permissions: ['read', 'write', 'delete']
};

console.log(checkAccess(user1, 'read')); // { allowed: true, reason: 'Access granted' }
console.log(checkAccess(user2, 'delete')); // { allowed: true, reason: 'Admin access' }
console.log(checkAccess(null, 'read')); // { allowed: false, reason: 'User not found or inactive' }
Swipe to see more code

🎯 Practice Exercise

Test your understanding of this topic:

Ready for the Next Module?

Continue your learning journey and master the next set of concepts.

Continue to Module 3