Conditional statements are used to perform different actions based on different conditions. They allow your program to make decisions and execute specific blocks of code only when certain criteria are met.
Use the if statement to specify a block of JavaScript code to be executed if a
condition is true.
if (condition) {
// block of code to be executed if the condition is true
}
Example: Greeting based on time.
if (hour < 12) {
greeting = "Good morning";
}
Use the else statement to specify a block of code to be executed if the
condition is false.
if (hour < 18) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
Use the else if statement to specify a new condition if the first condition is
false. You can use as many else if blocks as you need.
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
You can put an if statement inside another if statement. This is
known as nesting.
if (userLoggedIn) {
if (hasSubscription) {
console.log("Welcome to Premium Content");
} else {
console.log("Please subscribe");
}
}
if: Executes code only if a condition is trueelse: Executes code if the same condition is falseelse if: Adds more conditions to the sequence(){}