Today I learned how to make decisions in JavaScript using the if...else statement — and here’s a visual walkthrough for anyone else just getting started!
What is if...else?
In plain English:
"If something is true, do one thing. Otherwise, do something else."
Diagram: Basic Flow
[condition]
↓
true → Run this code
↓
false → Run this other code
Example 1: Checking Age
let age = 18;
if (age >= 18) {
console.log("You're an adult!");
} else {
console.log("You're a minor!");
}
Visual: What’s Happening
| Variable | Condition Checked | Result | Output |
|---|---|---|---|
age = 18 |
age >= 18 → true
|
✅ true block | "You're an adult!" |
Example 2: Using else if for Grades
let score = 75;
if (score >= 90) {
console.log("A grade");
} else if (score >= 80) {
console.log("B grade");
} else if (score >= 70) {
console.log("C grade");
} else {
console.log("Needs improvement");
}
🖼️ Visual: Grading Flowchart
[score]
↓
score ≥ 90 → A grade
↓
score ≥ 80 → B grade
↓
score ≥ 70 → C grade
↓
else → Needs improvement
Summary Table
| Score | Output |
|---|---|
| 95 | A grade |
| 82 | B grade |
| 75 | C grade |
| 60 | Needs improvement |
Tips for Beginners
- Use indentation to make
if...elseblocks easy to read. - Always test your conditions with different values.
- You can combine conditions with
&&(AND) and||(OR) later.
Final Thoughts
Learning if...else gave me a real "aha!" moment. It’s like teaching your code to think logically. I’m excited to keep going and try out more complex conditions next!
👀 Stay tuned for my next post: &&, ||, and switch in JavaScript.
Happy coding!
Top comments (0)