JavaScript if...Else
Statement
Conditional statements are used to perform different actions based on different conditions.
Conditional Statements
When writing code, you often need to perform different actions for different decisions. You can use conditional statements in your code to accomplish this task.
In JavaScript, we can use the following conditional statements:
- if statement - Executes code only if the specified condition is true
- if...else statement - Executes code if the condition is true and another code if the condition is false
- if...else if....else statement - Selects one of multiple code blocks to execute
- switch statement - Selects one of multiple code blocks to execute
if Statement
The statement executes code only if the specified condition is true.
Syntax
Use lowercase if. Using uppercase letters (IF) will generate a JavaScript error!
Example
Generates a greeting "Good day" if the time is less than 20:00:
if (time < 20) {
x = "Good day";
}
The result of x is:
var d = new Date();
var time = d.getHours();
if (time < 20) {
document.write("Good day");
}
Note that there is no ..else..
in this syntax. You have told the browser to execute the code only if the specified condition is true.
if...else Statement
Use the if....else
statement to execute code if the condition is true and another code if the condition is false.
Syntax
Example
Generates a greeting "Good day" if the time is less than 20:00, otherwise generates a greeting "Good evening":
if (time < 20) {
x = "Good day";
} else {
x = "Good evening";
}
The result of x is:
var d = new Date();
var time = d.getHours();
if (time < 20) {
document.write("Good day");
} else {
document.write("Good evening");
}
if...else if...else Statement
Use the if....else if...else
statement to select one of multiple code blocks to execute.
Syntax
Example
If the time is less than 10:00, generates a greeting "Good morning", if the time is between 10:00 and 20:00, generates a greeting "Good day", otherwise generates a greeting "Good evening":
if (time < 10) {
document.write("<b>Good morning</b>");
} else if (time >= 10 && time < 20) {
document.write("<b>Good day</b>");
} else {
document.write("<b>Good evening!</b>");
}
The result of x is:
var d = new Date();
var time = d.getHours();
if (time < 10) {
document.write("<b>Good morning</b>");
} else if (time >= 10 && time < 16) {
document.write("<b>Good day</b>");
} else {
document.write("<b>Good evening!</b>");
}