DEV Community

Tamilselvan K
Tamilselvan K

Posted on

Day -19πŸ”€ Getting Started with `if...else` in JavaScript (With Visuals!)

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
Enter fullscreen mode Exit fullscreen mode

πŸ§ͺ Example 1: Checking Age

let age = 18;

if (age >= 18) {
  console.log("You're an adult!");
} else {
  console.log("You're a minor!");
}
Enter fullscreen mode Exit fullscreen mode

πŸ–ΌοΈ 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");
}
Enter fullscreen mode Exit fullscreen mode

πŸ–ΌοΈ Visual: Grading Flowchart

      [score]
         ↓
score β‰₯ 90 β†’ A grade
   ↓
score β‰₯ 80 β†’ B grade
   ↓
score β‰₯ 70 β†’ C grade
   ↓
     else β†’ Needs improvement
Enter fullscreen mode Exit fullscreen mode

βœ… 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)