Codetainer LogoCodetainer Acad

Lessons

Lesson 19: Conditionals and Loops

πŸ” Lesson 19: Conditionals and Loops

Sometimes in your code, you want to make decisions β€” "Do this if the user is logged in", "Repeat this task 5 times", etc. JavaScript gives us tools to make those decisions and run repeated tasks.

🧠 Conditionals – Making Decisions

1. if...else

The simplest conditional. If the condition is true, run the first block. Otherwise, run the second.


let age = 20;

if (age >= 18) {
  console.log("Adult");
} else {
  console.log("Minor");
}

2. if...else if...else

You can chain multiple conditions. JavaScript checks them top to bottom and runs the first one that’s true.


let score = 75;

if (score >= 90) {
  console.log("A");
} else if (score >= 80) {
  console.log("B");
} else if (score >= 70) {
  console.log("C");
} else {
  console.log("F");
}

3. switch

A cleaner way to handle many exact matches. Useful when comparing one value to many possibilities.


let day = "Monday";

switch (day) {
  case "Monday":
    console.log("Start of the week!");
    break;
  case "Friday":
    console.log("Almost weekend!");
    break;
  case "Sunday":
    console.log("Rest day.");
    break;
  default:
    console.log("Just another day.");
}

πŸ’‘ Use break to stop the switch from falling through to other cases.

πŸ” Loops – Repeating Tasks

1. for loop

Great when you know how many times to repeat something.


for (let i = 0; i < 5; i++) {
  console.log("Number:", i);
}

This loop prints numbers 0 to 4. It has 3 parts:

  • let i = 0: Start
  • i < 5: Keep going while this is true
  • i++: Increase i after every loop

2. while loop

Keeps running as long as the condition is true.


let i = 0;

while (i < 5) {
  console.log(i);
  i++;
}

If you forget to increase i, it’ll loop forever. Be careful. ☠️

3. do...while loop

This loop always runs at least once, even if the condition is false.


let i = 0;

do {
  console.log(i);
  i++;
} while (i < 5);

Useful when you want to show something first, then check if you should continue.

βœ… Recap

  • if checks a condition
  • else if lets you test more cases
  • switch is great for matching exact values
  • for is perfect for counting
  • while runs as long as something is true
  • do...while runs once, then checks

Next up, we'll learn how to organize logic into functions so we can reuse code and clean up our programs!

CodetainerAcad