JavaScript if...else Statement
In JavaScript, if.else statement is employed to make choices. It enables you to run a block of code if a certain condition is true and another block of code if the condition is not true.
There are three forms of if-else statements in JavaScript:
- if statement
- if...else statement
- if...else ladder statement
If Statement
The if statement helps in running a piece of code when a specified condition is satisfied.
Syntax:
if (condition){
// block of code to be executed if the condition is true
}
Example:
let x
=
8;
if (x
> 5)
{
console.log("x is greater than 5");
}
Output:
x is greater than 5
If...else statement
The if...else statement is employed to run a block of code when a given condition is true and another block of code when the condition is false.
Syntax:
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
}
Example:
let x
=
8;
if (x
> 5)
{
console.log("x is greater than 5");
} else {
console.log("x is not greater than 5");
}
Output:
x is greater than 5
If else ladder
Syntax:
if (condition) {
// 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
}
Example:
let x
=
10;
if (x
> 15)
{
console.log("x is greater than 15");
}
else if
(x > 10)
{
console.log("x is greater than 10 but less than or equal to 15");
}
else {
console.log("x is equal to 10");
}
Output:
x is equal to 10