Conditional statements in JavaScript are used to control the flow of code execution based on certain conditions. In this article, we will discuss the if-else statement, one of the most important conditional statements in JavaScript.
The if-else statement allows us to execute a block of code if a certain condition is true, and a different block of code if the condition is false. The basic syntax of the if-else statement in JavaScript is as follows:
if (condition) {
// code to be executed if the condition is true
} else {
// code to be executed if the condition is false
}
Let’s take a look at a few examples to understand how the if-else statement works:
Example 1: Checking if a number is positive or negative
let num = -3;
if (num >= 0) {
console.log("The number is positive.");
} else {
console.log("The number is negative.");
}
In this example, the condition num >= 0
is checked. If the condition is true, the message “The number is positive.” is printed on the console. Otherwise, the message “The number is negative.” is printed.
Example 2: Checking if a number is even or odd
let num = 6;
if (num % 2 == 0) {
console.log("The number is even.");
} else {
console.log("The number is odd.");
}
In this example, the condition num % 2 == 0
is checked. If the condition is true, the message “The number is even.” is printed on the console. Otherwise, the message “The number is odd.” is printed.
Example 3: Checking if a password is correct
let password = "mypass";
if (password == "mypass") {
console.log("Access granted.");
} else {
console.log("Access denied.");
}
In this example, the condition password == "mypass"
is checked. If the condition is true, the message “Access granted.” is printed to the console. Otherwise, the message “Access denied.” is printed.
We can also use the if-else statement in combination with other conditional statements, such as the else if statement, to check multiple conditions. Here is an example:
Example 4: Checking the grade of a student
let marks = 90;
if (marks >= 90) {
console.log("Grade A");
} else if (marks >= 80) {
console.log("Grade B");
} else if (marks >= 70) {
console.log("Grade C");
} else {
console.log("Grade F");
}
In this example, the marks of the student are checked against multiple conditions using the else if statement. If the marks are greater than or equal to 90, grade A is printed on the console. If the marks are between 80 and 89, grade B is printed. If the marks are between 70 and 79, grade C is printed. If the marks are less than 70, grade F is printed.
In conclusion, an if-else statement is a powerful tool for controlling the flow of code execution in JavaScript. By using the if-else statement, we can check multiple conditions and execute different blocks of code based on those conditions. This allows us to create more robust and flexible code.