In programming, making decisions based on conditions is crucial. JavaScript provides conditional statements, specifically the if…else statement and its variations, to control the flow of your code depending on whether certain conditions are true or false.
The if Statement: The Foundation of Conditional Logic
The if statement allows you to execute a block of code only if a specified condition is true. Here’s the syntax:
if (condition) {
// Code to be executed if the condition is true
}
- condition: This is a JavaScript expression that evaluates to either true or false. Common expressions involve comparisons using operators like >, <, ==, !=.
Example:
let age = 20;
if (age >= 18) {
console.log(“You are eligible to vote.”);
}
In this example, if age is 18 or greater (including 18), the message “You are eligible to vote” will be printed to the console.
The if…else Statement: Handling Both True and False Scenarios
The if…else statement lets you execute different code blocks based on the condition’s truth value. Here’s the syntax:
if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}
Example:
let grade = 85;
if (grade >= 90) {
console.log(“Excellent!”);
} else {
console.log(“Good job, keep practicing!”);
}
Here, if grade is 90 or higher, “Excellent!” is displayed. Otherwise, “Good job, keep practicing!” is displayed.
The if…else if…else Statement: Making Multiple Choices
The if…else if…else statement (often called an if-else ladder) allows you to check multiple conditions sequentially. Here’s the syntax:
if (condition1) {
// Code to be executed if condition1 is true
} else if (condition2) {
// Code to be executed if condition1 is false and condition2 is true
} else if (condition3) {
// Code to be executed if both condition1 and condition2 are false and condition3 is true
} else {
// Code to be executed if none of the conditions are true
}
Example:
let number = -5;
if (number > 0) {
console.log(“The number is positive.”);
} else if (number < 0) {
console.log(“The number is negative.”);
} else {
console.log(“The number is zero.”);
}
In this example, the code checks if the number is positive, negative, or zero, printing the corresponding message.
Remember: The else if blocks are evaluated only if the preceding conditions are false. The else block executes if none of the conditions in the if or else if statements are true.
By effectively using conditional statements, you can write more flexible and interactive JavaScript programs that respond to different scenarios.
Source: hashnode.com