Control Flow

Overview

Control flow refers to the order in which individual statements, instructions, or function calls are executed or evaluated. By default, code runs sequentially, but control flow structures allow the program to skip sections or repeat them based on conditions.

Core Concepts

  • Conditional Branching: Making decisions to execute different blocks of code.
    • If/Else: The most basic binary choice.
    • Else If / Switch: Handling multiple possible conditions.
    • Ternary Operator: A shorthand for simple if/else assignments (condition ? expr1 : expr2).
  • Boolean Logic: The foundation of control flow, using operators like AND (&&), OR (||), and NOT (!).
  • Short-Circuit Evaluation: When the second operand of a boolean operation is not evaluated because the first is sufficient to determine the result.
  • Guard Clauses: Using an early return or throw to exit a function if a condition is not met, reducing nested if-statements.

Code Examples

// If/Else and Ternary
let age = 20;
let status = (age >= 18) ? "Adult" : "Minor";

if (age < 13) {
    console.log("Child");
} else if (age < 20) {
    console.log("Teenager");
} else {
    console.log("Adult");
}

// Switch Statement
let day = "Monday";
switch (day) {
    case "Monday":
        console.log("Start of the week!");
        break;
    case "Friday":
        console.log("Weekend is near!");
        break;
    default:
        console.log("Just another day.");
}

Use Cases

  • Input Validation: Checking if user input is valid before processing it.
  • Game Logic: Determining character state (e.g., if (health <= 0) { gameOver(); }).
  • Feature Flags: Enabling or disabling features based on a configuration toggle.

Gotchas

  • Deep Nesting: The "Pyramid of Doom" where multiple nested if-statements make code unreadable. Solution: Use guard clauses.
  • Switch Fall-through: Forgetting the break keyword in a switch statement, causing the code to execute subsequent cases regardless of the condition.
  • Truthiness/Falsiness: In languages like JS, values like 0, "", null, and undefined are "falsy", which can cause unexpected behavior in loose checks.

Related Notes