Conditional statements are an essential part of programming in JavaScript. They allow you to control the flow of your code based on certain conditions. Think of it as a way for your program to make decisions.
What Are Conditional Statements?
Conditional statements check if a specific condition is true or false and execute a block of code based on that result. The most common conditional statements in JavaScript are:
- if Statement
- else Statement
- else if Statement
- switch Statement
Examples:
1. if Statement The if
statement is the simplest form. It runs a block of code if the condition is true.
In this example, if age
is 18 or older, the program will print “Access granted.”
2. if…else Statement The else
part runs if the condition is false.
Here, if age
is less than 18, it will show “Access denied.”
3. else if Statement Use else if
to add more conditions.
This checks multiple conditions and decides which message to show.
4. switch Statement The switch
statement is useful when you have multiple possible conditions for a single variable.
It checks the value of day
and matches it with the cases. If none match, it goes to default
.
Why Use Conditional Statements?
- Decision Making: It helps your code decide what to do next.
- Simplifies Code: Avoids writing multiple
if
statements. - Easy to Understand: More readable than nested code blocks.
Best Practices
- Keep conditions simple.
- Avoid unnecessary nesting.
- Use
switch
for handling multiple cases.
Statement | Description | Syntax Example | Use Case |
if | Executes code if a condition is true. | if (x > 5) { … } | Check if a user is logged in before showing content. |
if…else | Runs code if true; otherwise, runs an alternative code. | if (x > 5) { … } else { … } | Show “Access denied” if the user is under 18. |
else if | Adds more conditions to an if statement. | if (x > 5) { … } else if (x < 3) { … } | Check multiple ranges (e.g., grading scores). |
switch | Evaluates an expression and matches it to case blocks. | switch(day) { case 1: … break; default: … } | Handling multiple options like menu selection. |