1. if
Use the JavaScript if statement to execute a block of code when a condition is true.
if (condition) {
// block of code to be executed if the condition is true
}
if (age >= 18) {
console.log("You can drive!");
}
2. Nested if
You can use an if statement inside another if statement:
let age = 18;
let country = "India";
let text = "You can Not drive!";
if (country == "India") {
if (age >= 18) {
text = "You can drive!";
}
}
Nested if statements can make your code more complex.A better solution is to use the logical AND operator:
let age = 18;
let country = "India";
let text = "You can Not drive!";
if (country == "India" && age >= 18) {
text = "You can drive!";
}
3. The else Statement
Use the else statement to specify a block of code to be executed if a condition is false.
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
if (age >= 18) {
console.log("You can drive!");
} else {
console.log("You can Not drive!");
}
4. The else if Statement
Use the else if statement to specify a new condition if the first is false.
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
Top comments (0)