Module 1: Control Flow
If...Else & Switch
let age = 20;
if (age >= 18) {
console.log("You can vote");
} else if (age >= 13) {
console.log("You're a teenager");
} else {
console.log("You're a child");
}
switch is a cleaner alternative when checking one value against many possibilities:
let day = "Mon";
switch (day) {
case "Mon":
case "Tue":
case "Wed":
case "Thu":
case "Fri":
console.log("Weekday");
break;
case "Sat":
case "Sun":
console.log("Weekend");
break;
default:
console.log("Invalid day");
}
Don't forget break β without it, execution falls through into the
next case, which is sometimes intentional (grouping MonβFri above) but usually a bug otherwise.
For, While & Do-While
for (let i = 0; i < 5; i++) {
console.log(i); // 0, 1, 2, 3, 4
}
let fruits = ["apple", "banana", "mango"];
for (let fruit of fruits) { // for...of β loops over VALUES
console.log(fruit);
}
let user = { name: "Chiru", age: 25 };
for (let key in user) { // for...in β loops over KEYS, used for objects
console.log(key, user[key]);
}
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
let j = 10;
do { // runs the body at least ONCE, even if condition starts false
console.log(j);
j++;
} while (j < 5);
Break & Continue
for (let i = 0; i < 10; i++) {
if (i === 5) break; // exits the loop entirely
console.log(i); // 0, 1, 2, 3, 4
}
for (let i = 0; i < 5; i++) {
if (i === 2) continue; // skips to the next iteration
console.log(i); // 0, 1, 3, 4
}