Control program flow (Conditional Statements and Looping Statements)

 

Control flow determines the order in which your code executes. Without it, scripts would just run from the first line to the last without any logic.
 
1. Conditional Statements
Conditionals allow your code to make decisions—running specific blocks of code only if a condition is met.
 
  • if statement: The most basic decision maker.
     
    if (age >= 18) {
      console.log("You can vote.");
    }
  • else and else if: Used to handle multiple outcomes.
     
    if (score >= 90) {
      console.log("Grade A");
    } else if (score >= 75) {
      console.log("Grade B");
    } else {
      console.log("Try again");
    }
    
     
     
  • switch statement: A cleaner way to check a single variable against many different values.
     
    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.");
    }
    
     
2. Looping Statements
Loops are used to repeat a block of code multiple times until a certain condition is met.
 
  • for loop: Best when you know exactly how many times you want to repeat.
    javascript
    for (let i = 0; i < 5; i++) {
      console.log("Count is: " + i);
    }
  • while loop: Repeats as long as a condition remains true. Use this when the number of loops is unknown.
     
    while (battery > 0) {
      console.log("Phone is on");
      battery--; 
    }
    
     
     
  • do...while loop: Similar to while, but it guarantees the code runs at least once before checking the condition.