Conditional statements allow your code to make decisions and execute different blocks of code based on conditions. This is essential for creating dynamic and responsive applications.
Types of Conditional Statements
if
: Executes a block of code if a specified condition is true
.else
: Executes a block of code if the same condition is false
.else if
: Tests a new condition if the first one is false
.switch
: Provides multiple alternative blocks of code for execution (covered in another section)
The if
Statement
The if
statement executes a block of code if a specified condition evaluates to true
.
Syntax
if (condition) {
// Code to execute if the condition is true
}
Example
let hour = 15;
if (hour < 18) {
console.log("Good day");
}
// Output: Good day
The else
Statement
The else
statement executes a block of code when the if
condition is false
.
Syntax
if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}
Example
let hour = 20;
if (hour < 18) {
console.log("Good day");
} else {
console.log("Good evening");
}
// Output: Good evening
The else if
Statement
The else if
statement allows you to check multiple conditions in sequence.
Syntax
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition1 is false and condition2 is true
} else {
// Code to execute if both conditions are false
}
Example
let time = 9;
if (time < 10) {
console.log("Good morning");
} else if (time < 20) {
console.log("Good day");
} else {
console.log("Good evening");
}
// Output: Good morning
Example: Random Link Selection
This example demonstrates conditional logic using a random number to choose between two links.
let text;
if (Math.random() < 0.5) {
text = "Visit JavaScript Guide";
} else {
text = "Visit Wildlife Conservation";
}
console.log(text);
Possible Outputs:
Visit JavaScript Guide
OR
Visit Wildlife Conservation