How to Write Conditional Statements in JavaScript


Conditional statements in JavaScript allow you to control the flow of your code by making decisions based on certain conditions. In this guide, we'll explore how to write conditional statements in JavaScript and provide examples to illustrate each concept.


The If Statement


The if statement is used to execute a block of code if a specified condition is true:


let age = 18;
if (age >= 18) {
console.log("You are an adult.");
}

The If-Else Statement


The if-else statement allows you to execute one block of code if a condition is true and another block if it's false:


let hour = 14;
if (hour < 12) {
console.log("Good morning!");
} else {
console.log("Good afternoon!");
}

The If-Else-If Statement


The if-else-if statement lets you test multiple conditions in sequence and execute the first block that is true:


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

The Switch Statement


The switch statement is used to evaluate an expression against multiple possible case values:


let day = "Tuesday";
let message = "";
switch (day) {
case "Monday":
message = "It's the start of the week.";
break;
case "Tuesday":
case "Wednesday":
message = "It's the middle of the week.";
break;
default:
message = "It's the end of the week.";
}
console.log(message);

Conditional Ternary Operator


The conditional (ternary) operator provides a compact way to write simple if-else statements:


let isAdult = true;
let status = isAdult ? "You are an adult" : "You are not an adult";
console.log(status);

Conclusion


Conditional statements are essential for making decisions in your JavaScript code. They allow you to execute different code blocks based on specific conditions. Understanding how to use if, if-else, if-else-if, switch, and the ternary operator is crucial for effective JavaScript programming.


Happy coding!