Logic Brain Gym: Mastering Control Flow
This is where JavaScript stops being just a language
and starts becoming a way of thinking.
βAt this stage, you either level upβ¦ or give up. We level up.β
π Conditions: if, else if, else
Logic in JavaScript starts with one simple question:
If this is true, what should happen? If not, then what?
JavaScript
if (condition) {
// runs if true
} else {
// runs if false
}
Real-life example:
JavaScript
let age = 18;
if (age >= 17) {
console.log("You may enter the cinema π¬");
} else {
console.log("Sorry, not old enough π
");
}
JavaScript has zero empathy. True runs. False gets skipped.
βοΈ Comparison Operators & Booleans
| Operator | Meaning |
|---|---|
| == | Equal value (not recommended) |
| === | Equal value & type (USE THIS) |
| != | Not equal |
| > | Greater than |
| < | Less than |
| >= | Greater or equal |
| <= | Less or equal |
JavaScript
console.log(5 === "5"); // false
console.log(5 === 5); // true
Boolean values are brutally simple: true or false. No middle ground.
π Logical Operators
| Operator | Meaning |
|---|---|
| && | AND |
| || | OR |
| ! | NOT (reverse) |
JavaScript
let age = 20;
let hasTicket = true;
if (age >= 17 && hasTicket) {
console.log("Welcome to the cinema πΏ");
}
π§ Switch Case
When conditions get messy, switch keeps things readable.
JavaScript
let day = "Monday";
switch (day) {
case "Monday":
console.log("Time to work πΌ");
break;
case "Sunday":
console.log("Rest day π΄");
break;
default:
console.log("Just another day");
}
Forget break?
Everything below it runs. Chaos mode activated.
π Loops: Repeat Without Crying
for loop
JavaScript
for (let i = 1; i <= 5; i++) {
console.log("Count:", i);
}
while loop
JavaScript
let count = 1;
while (count <= 3) {
console.log(count);
count++;
}
do while loop
JavaScript
let num = 1;
do {
console.log(num);
num++;
} while (num <= 3);
π§ͺ Practice Time
Odd / Even Check
JavaScript
let number = 7;
if (number % 2 === 0) {
console.log("Even");
} else {
console.log("Odd");
}
Multiple Check
JavaScript
let num = 20;
if (num % 5 === 0) {
console.log("Multiple of 5");
} else {
console.log("Not a multiple of 5");
}
ποΈ Mini Program: Cinema Ticket
JavaScript
let age = 19;
let money = 50000;
if (age >= 17 && money >= 40000) {
console.log("Ticket purchased π¬");
} else {
console.log("Requirements not met π");
}
This is real-world logic. Programming is decision-making, not math.
π₯ Mini Challenges
- FizzBuzz (3, 5, 3 & 5)
- Loop 1β10 β Odd / Even
- Login simulation (username & password)
Try first. Donβt peek. Your brain needs reps.
