JavaScript is one of the most widely used programming languages in web development. One of the fundamental features of this language is conditional statements. The if, else, and else if statements allow different parts of the program to execute based on certain conditions. In this article, we will explore the use of if, else, and else if in JavaScript.
If Statement
The if statement allows a specific block of code to run when a given condition is true. For example:
if (condition) {
// This block of code runs if the condition is true
}
For instance, let’s check a user’s age and display a message if the age is greater than 18:
let age = 20;
if (age > 18) {
console.log("Your age is greater than 18.");
}
Else Statement
The else statement provides an alternative block that runs if the condition in the if statement is false. For example:
if (condition) {
// This block of code runs if the condition is true
} else {
// This block of code runs if the condition is false
}
For example, let’s check a user’s age and print “Adult” if the age is greater than 18, or “Child” if it’s not:
let age = 15;
if (age > 18) {
console.log("Adult");
} else {
console.log("Child");
}
Else If Statement
The else if statement checks another condition if the initial condition is false and runs the corresponding block of code if the new condition is true. For example:
if (condition1) {
// This block of code runs if condition1 is true
} else if (condition2) {
// This block of code runs if condition2 is true
} else {
// This block of code runs if neither condition1 nor condition2 is true
}
For example, let’s check a user’s age and display different messages depending on the age:
let age = 25;
if (age < 18) {
console.log("Child");
} else if (age < 65) {
console.log("Adult");
} else {
console.log("Retired");
}
This code will print “Child”, “Adult”, or “Retired” depending on the user’s age.
Conclusion
In JavaScript, the if, else, and else if statements are powerful tools that allow programs to behave according to specific conditions. By using these statements correctly, you can make your code more flexible and predictable. Therefore, it’s important to understand these conditional statements well when learning JavaScript.