Conditional Statements in JavaScript

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:

  1. if Statement
  2. else Statement
  3. else if Statement
  4. switch Statement

Examples:

1. if Statement The if statement is the simplest form. It runs a block of code if the condition is true.

let age = 20;
if (age >= 18) {
console.log("Access granted");
}

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.

let age = 16;
if (age >= 18) {
console.log("Access granted");
} else {
console.log("Access denied");
}

Here, if age is less than 18, it will show “Access denied.”

3. else if Statement Use else if to add more conditions.

let score = 85;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B");
} else {
console.log("Grade: C");
}

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.

let day = 3;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default:
console.log("Invalid day");
}

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.
StatementDescriptionSyntax ExampleUse Case
ifExecutes code if a condition is true.if (x > 5) { … }Check if a user is logged in before showing content.
if…elseRuns code if true; otherwise, runs an alternative code.if (x > 5) { … } else { … }Show “Access denied” if the user is under 18.
else ifAdds more conditions to an if statement.if (x > 5) { … } else if (x < 3) { … }Check multiple ranges (e.g., grading scores).
switchEvaluates an expression and matches it to case blocks.switch(day) { case 1: … break; default: … }Handling multiple options like menu selection.
Scroll to Top