If Statement in JavaScript
1. Purpose
- The if statement is a fundamental control flow structure in JavaScript.
- It allows your code to make decisions based on whether a specific condition is true or false.
2. Syntax
if (condition) {
// Code to be executed if the condition is true
}
- condition: This is an expression that evaluates to either true or false.
- It can use comparison operators (e.g., >, <, ==, ===), logical operators (&&, ||, !), or other expressions that result in a boolean value.
3. Example:
let age = 25;
if (age >= 18) {
console.log("You are an adult.");
}
In this example, The if statement will check if the value of the age variable is greater than or equal to 18.
- If the condition is true1 (age is 18 or older), the code inside the curly braces will execute, and the message “You are an adult.” will be printed to the console.
- If the condition is false (age is less than 18), the code inside the curly braces will be skipped, and nothing will be printed to the console.
if...else Statement in JavaScript
1. Purpose
- You can use the else keyword to provide an alternative block of code to be executed if the condition is false.
2. Example:
let age = 15;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}
if...else if...else Statement in JavaScript
1. Purpose
- You can chain multiple if…else if blocks to handle more complex conditions.
2. Example:
let grade = 90;
if (grade >= 90) {
console.log("Excellent!");
} else if (grade >= 80) {
console.log("Good job!");
} else if (grade >= 70) {
console.log("Satisfactory.");
} else {
console.log("Needs improvement.");
}