JavaScript Fundamentals

Control Flow and Loops

Understanding Control Flow and Loops

Control flow statements and loops are essential for creating dynamic and efficient programs. They allow you to make decisions in your code and repeat actions without writing redundant code.

Conditional Statements

// If-Else Statements
let age = 18;
if (age >= 18) {
  console.log("You can vote!");
} else {
  console.log("Too young to vote.");
}

// 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("Regular day");
}

Loop Types

// For Loop
for (let i = 0; i < 5; i++) {
  console.log(`Count: ${i}`);
}

// While Loop
let count = 0;
while (count < 3) {
  console.log(`While count: ${count}`);
  count++;
}

// For...of Loop (Arrays)
let colors = ['red', 'green', 'blue'];
for (let color of colors) {
  console.log(color);
}

Advanced Control Flow

// Break and Continue
for (let i = 0; i < 5; i++) {
  if (i === 2) continue; // Skip 2
  if (i === 4) break;    // Stop at 4
  console.log(i);
}

// Nested Loops
for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 2; j++) {
    console.log(`i: ${i}, j: ${j}`);
  }
}