Conditional Statement
In JavaScript, conditional statements are used to perform different actions based on different conditions. They allow your program to make decisions and execute code selectively, depending on whether a condition is true or false.
There are three types of conditional statements in JavaScript: if, else if, and else.
1. if statement
2. if...else statement
3. if...else if...else statement
4. switch statement
1. if statement:
Executes a block of code if the condition is true.
Syntax
if (condition) {
// code to be executed if condition is true
}
Example
let x = 10;
if (x > 5) {
console.log("x is greater than 5");
}
2. if else statement:
Executes one block of code if the condition is true and another block if it is false.
Syntax
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
Example
let x = 10;
if (x > 5) {
console.log("x is greater than 5");
} else {
console.log("x is less than or equal to 5");
}
3. if...else if...else statement
Checks multiple conditions and executes code based on the first true condition.
Syntax
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else {
// code to be executed if all conditions are false
}
Example
let x = 10;
if (x > 15) {
console.log("x is greater than 15");
} else if (x > 5) {
console.log("x is greater than 5");
} else {
console.log("x is less than or equal to 5");
}