The if-else
statement in JavaScript is used to perform different actions based on different conditions.
The if Statement
The if
statement executes a block of code if a specified condition is true.
Here’s an example:
let x = 10;
if (x > 5) {
console.log('x is greater than 5');
}
In this example, the message ‘x is greater than 5’ will be logged to the console because the condition x > 5
is true.
The else Statement
The else
statement executes a block of code if the same condition is false.
Here’s an example:
let x = 4;
if (x > 5) {
console.log('x is greater than 5');
} else {
console.log('x is not greater than 5');
}
In this example, the message ‘x is not greater than 5’ will be logged to the console because the condition x > 5
is false.
The else-if Statement
The else if
statement specifies a new condition if the first condition is false.
Here’s an example:
let x = 5;
if (x > 5) {
console.log('x is greater than 5');
} else if (x == 5) {
console.log('x is equal to 5');
} else {
console.log('x is less than 5');
}
In this example, the message ‘x is equal to 5’ will be logged to the console because the condition x == 5
is true.
The if-else
statement in JavaScript is a powerful tool for controlling the flow of your code. It allows you to execute different blocks of code based on different conditions. Understanding how to use the if-else
statement effectively is crucial to writing good JavaScript code.