DEV Community

Cover image for If It Happens... Else Do This! Understanding Conditions in JavaScript
Megha M
Megha M

Posted on

If It Happens... Else Do This! Understanding Conditions in JavaScript

Today I learned about conditional statements in JavaScript. These statements are the building blocks for decision-making in any program. I understood how we can control the flow of the program based on certain conditions using if, else, else if, and even nested if blocks.

What is a Conditional Statement?

Conditional statements let the program decide what to do next based on whether a condition is true or false.

In JavaScript, we use these:

  • if – checks a condition and runs the code if it’s true
  • else – runs when the if condition is false
  • else if – checks multiple conditions in order
  • nested if – an if inside another if, used for complex logic

Flowchart: How Conditional Statements Work

 [Start] | [Condition] / \ True False / \ [If block] [Else block] | [Else if block] (optional) | [End] 
Enter fullscreen mode Exit fullscreen mode

Problem I Solved: Grade Calculator

Problem Statement:

Write a program to accept a student’s mark and print the grade based on the mark.

Code:

let marks = 85; if (marks >= 90) { console.log("Grade A"); } else if (marks >= 80) { console.log("Grade B"); } else if (marks >= 70) { console.log("Grade C"); } else if (marks >= 60) { console.log("Grade D"); } else { console.log("Grade F"); } 
Enter fullscreen mode Exit fullscreen mode

  • The program checks one condition at a time.
  • Once a condition is true, it prints the corresponding grade and stops checking further.
  • If none match, it goes to the final else block (Grade F).

Ask Yourself: What Are the Alternatives?

Can you solve the same problem using any of these?

  • Ternary Operator
  • switch(true) statement
  • Function-based logic
  • Nested if

Challenge for You:

Try rewriting this same grade logic using one of the above methods and see which is shorter or easier to understand!

What I Learned

Conditional statements help in making programs dynamic and responsive. Whether it's grading students, checking login info, or greeting users based on time — they are used everywhere. I’ll keep practicing to get more confident with different structures.

Top comments (2)

Collapse
 
little_coding_things profile image
Little Coding Things Blog

I liked the "Challenge for you" section. Very nice post, well written and solid structure. Keep up the good work!

Collapse
 
megha_m profile image
Megha M

Thank you