Conditional statements allow you to execute certain blocks of code based on specific conditions.
JavaScript provides several types of conditional statements, including if
, else
, else if
, and switch
.
Conditional Statements in JavaScript
Using the If Statement
let temperature = 30;
if (temperature > 25) {
console.log("It's a hot day!");
}
In this example, the message "It's a hot day!" will be logged to the console if the temperature is greater than 25.
Using the If...Else Statement
let temperature = 20;
if (temperature > 25) {
console.log("It's a hot day!");
} else {
console.log("It's a cool day!");
}
Here, if the temperature is not greater than 25, the message "It's a cool day!" will be displayed instead.
Using Else If for Multiple Conditions
let temperature = 15;
if (temperature > 25) {
console.log("It's a hot day!");
} else if (temperature > 15) {
console.log("It's a warm day!");
} else {
console.log("It's a cool day!");
}
This example checks multiple conditions and executes the corresponding block based on the temperature value.
Using the Switch Statement
let fruit = "apple";
switch (fruit) {
case "banana":
console.log("Banana is yellow.");
break;
case "apple":
console.log("Apple is red or green.");
break;
case "grape":
console.log("Grapes are purple.");
break;
default:
console.log("Unknown fruit.");
}
In this example, the switch statement checks the value of fruit
and executes the corresponding case. If none of the cases match, the default case will run.
Conclusion
Conditional statements are essential for controlling the flow of execution in JavaScript programs. By using if
, else
, else if
, and switch
, you can make your code responsive to different conditions and inputs.
Note: We aim to make learning easier by sharing top-quality tutorials, but please remember that tutorials may not be 100% accurate, as occasional mistakes can happen. Once you've mastered the language, we highly recommend consulting the official documentation to stay updated with the latest changes. If you spot any errors, please feel free to report them to help us improve.