#javascript
#tutorial
#beginner
Day 2: Control Flow & Loops
Day 2: Making Decisions
Code isnāt just a list of instructions from top to bottom. Sometimes we need to branch (if this, then that) or loop (do this 10 times).
1. If / Else Statements
The most basic building block of logic.
const hour = 14; // 2 PM
if (hour < 12) {
console.log("Good Morning!");
} else if (hour < 18) {
console.log("Good Afternoon!");
} else {
console.log("Good Evening!");
}
Truthy & Falsy
In JS, values can be evaluated as true or false.
- Falsy:
false,0,""(empty string),null,undefined,NaN. - Truthy: Everything else (including
"0",[],{}).
const username = "";
if (username) {
console.log(`Welcome ${username}`);
} else {
console.log("Please log in."); // This runs because "" is falsy.
}
2. Switch Statements
Great for checking a single variable against multiple specific values.
const role = "admin";
switch (role) {
case "admin":
console.log("Full Access");
break;
case "editor":
console.log("Edit Access");
break;
default:
console.log("Read Only");
}
3. Loops
For Loop
Use when you know exactly how many times you want to repeat something.
for (let i = 0; i < 5; i++) {
console.log(`Iteration number ${i}`);
}
// Output: 0, 1, 2, 3, 4
While Loop
Use when you want to loop until a condition is met (be careful of infinite loops!).
let count = 0;
while (count < 3) {
console.log("Still going...");
count++;
}
Homework for Day 2:
- Write a program that checks a variable
age. - If age < 13, log āChildā.
- If age between 13 and 19, log āTeenagerā.
- Otherwise, log āAdultā.
- Bonus: Use a loop to print all even numbers from 0 to 20.
Tomorrow, we organize our code with Functions!