JavaScript if, else, and else if
Conditional Statements
Frequently, when you write code, you need to do various things based on different choices.
You can use if statements in your code to achieve this.
In JavaScript, we use certain conditional statements:
- Use
if
to specify a block of code to be executed, if a specified condition is true - Use
else
to specify a block of code to be executed, if the same condition is false - Use
else if
to specify a new condition to test, if the first condition is false - Use
switch
to specify many alternative blocks of code to be executed
The switch
statement is described in the next chapter.
The if Statement
You can use the if
statement in JavaScript to run a specific set of code when a certain condition is met.
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
// block of code to be executed if the condition is true
}
Note that if
is in lowercase letters. Capital letters (if or IF) can cause a JavaScript error.
The else Statement
You can use the if
statement in JavaScript to run a specific set of code when a certain condition is met.
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
}
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
The else if Statement
You can use the else if
statement to set up an additional condition when the initial condition turns out to be untrue.
Syntax
if (condition1) {
// 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
}
// 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
}