JavaScript if, else, and else if

JavaScript if, else, and else if are conditional statements that allow you to execute different blocks of code based on different conditions.

if

The if statement is used to execute a block of code if a specified condition is true. The syntax is as follows:

if (condition) {
// code to execute if condition is true
}

The condition can be any expression that evaluates to a boolean value. If the condition is true, the code block inside the if statement is executed. Otherwise, the code block is skipped.

else

The else statement is used to execute a block of code if the condition in the if statement is false. The syntax is as follows:

if (condition) {
// code to execute if condition is true
} else {
// code to execute if condition is false
}

else if

The else if statement is used to test a new condition if the condition in the if statement is false. The syntax is as follows:

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 condition1 and condition2 are false
}

You can have as many else if statements as you need. The code blocks in the else if statements are executed in order, until one of the conditions evaluates to true. If none of the conditions evaluate to true, the code block in the else statement is executed.

Examples

The following examples show how to use if, else, and else if statements:

// Check if a number is even or odd
const number = 10;

if (number % 2 === 0) {
console.log("The number is even.");
} else {
console.log("The number is odd.");
}


// Output: “The number is even.”

// Check if a user is above or below the legal drinking age
const age = 21;

if (age >= 21) {
console.log("You are of legal drinking age.");
} else {
console.log("You are not of legal drinking age.");
}


// Output: “You are of legal drinking age.”

// Determine the grade a student received based on their exam score
const examScore = 85;

if (examScore >= 90) {
console.log("A");
} else if (examScore >= 80) {
console.log("B");
} else if (examScore >= 70) {
console.log("C");
} else if (examScore >= 60) {
console.log("D");
} else {
console.log("F");
}
// Output: “B”

Tips

Use curly braces ({}) to group the code blocks in your ifelse, and else if statements. This makes your code more readable and easier to maintain.

Use indentation to make your code more readable.

Test your code carefully to make sure it is working as expected.