๐Ÿ”„ Control Flow Statements in JavaScript

๐Ÿ“Œ Introduction

In JavaScript, control flow statements decide the order in which code runs. They help you make decisions (โœ…/โŒ), repeat tasks ๐Ÿ”, or exit early ๐Ÿšช. Think of them as traffic signals ๐Ÿšฆ guiding your programโ€™s journey.

๐Ÿง  Major Control Flow Statements

  • ๐Ÿ”€ Conditional Statements โž if, if...else, switch
  • ๐Ÿ” Looping Statements โž for, while, do...while
  • โน๏ธ Jump Statements โž break, continue, return

๐Ÿ“Œ Conditional Flow

Used to run different code based on conditions.

if...else Example

let age = 18;

if (age >= 18) {
  console.log("Adult โœ…");
} else {
  console.log("Minor โŒ");
}

switch Example

let fruit = "apple";

switch(fruit) {
  case "apple":
    console.log("๐ŸŽ Apple selected");
    break;
  case "banana":
    console.log("๐ŸŒ Banana selected");
    break;
  default:
    console.log("Unknown fruit โ“");
}

๐Ÿ“Œ Looping Flow

Loops help you repeat code until a condition is met.

Looping Statements Example

// for loop
for (let i = 1; i <= 5; i++) {
  console.log("Count:", i);
}

// while loop
let x = 1;
while (x <= 3) {
  console.log("x is", x);
  x++;
}

// do...while loop
let y = 1;
do {
  console.log("y is", y);
  y++;
} while (y <= 2);

๐Ÿ“Œ Jump Flow

These statements help you exit or skip parts of code.

Jump Statements Example

for (let i = 1; i <= 5; i++) {
  if (i === 3) {
    continue; // skips 3๏ธโƒฃ
  }
  if (i === 5) {
    break; // stops loop at 5๏ธโƒฃ
  }
  console.log(i);
}

function greet(name) {
  if (!name) {
    return "No name provided โŒ";
  }
  return "Hello " + name + " ๐Ÿ‘‹";
}

โšก Control Flow Overview

TypeStatementPurpose
Conditionalif, if...else, switchDecision making
Loopingfor, while, do...whileRepeat code
Jumpbreak, continue, returnAlter loop/exit function

Note

๐Ÿ’ก Tip: Use for when you know the number of iterations, use while when looping until a condition, and do...while when you want to run at least once.
>>"Control flow is the steering wheel ๐Ÿ›ž of your program โ€” without it, your code would just drive straight forever."

๐Ÿ”— Further Learning