JavaScript If Statement
The JavaScript `if` statement is used to execute a block of code based on a specified condition. If the condition is true, the code block will run. If the condition is false, it is skipped. There are various ways to use the if statement in JavaScript.
- if
- if-else
- if-else-if
- nested if
JavaScript If Statement
The `if` statement in JavaScript allows conditional execution of code based on a specified condition. The code within the `if` block executes only if the condition is true.
Syntax
if (condition) {
// code to be executed if condition is true
}
Flowchart of JavaScript If statement

Example
let number = 10;
if (number > 0) {
console.log("The number is positive.");
}
Output
JavaScript If-Else Statement
The `if-else` statement is used to execute one block of code if a condition is true, and another block if the condition is false.
Syntax
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
Flowchart of JavaScript If...else statement

Example
let number = -5;
if (number > 0) {
console.log("The number is positive.");
} else {
console.log("The number is negative.");
}
Output
JavaScript If-Else-If Statement
The `if-else-if` statement is a chain of multiple conditions that can be checked in sequence. It allows for testing multiple conditions in a single if-else structure.
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 both conditions are false
}
Example
let grade = 85;
if (grade >= 90) {
console.log("A grade");
} else if (grade >= 80) {
console.log("B grade");
} else if (grade >= 70) {
console.log("C grade");
} else {
console.log("Fail");
}
Output
JavaScript Nested If Statement
The nested `if` statement contains one `if` statement inside another. The inner `if` statement is only executed if the condition in the outer `if` statement is true.
Syntax
if (condition1) {
// code to be executed if condition1 is true
if (condition2) {
// code to be executed if condition2 is also true
}
}
Example
let age = 20;
let hasID = true;
if (age >= 18) {
if (hasID) {
console.log("Allowed to enter");
} else {
console.log("ID required");
}
} else {
console.log("Not allowed to enter");
}