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...else
blocks 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)