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: Starti < 5: Keep going while this is truei++: 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!