Conditional statements are used to perform different actions based on different conditions.
Very often when you write code, you want to perform different actions for different decisions.
You can use conditional statements in your code to do this.
In JavaScript we have the following conditional statements:
if
to specify a block of code to be executed, if a specified condition is trueelse
to specify a block of code to be executed, if the same condition is falseelse if
to specify a new condition to test, if the first condition is falseswitch
to specify many alternative blocks of code to be executedThe switch
statement is described in the next chapter.
Use the if
statement to specify a block of JavaScript code to be executed if a condition is true.
<span style="color: mediumblue;">if</span> (_condition_) {
<span style="color: green;">//</span>_ block of code to be executed if the condition is true_
}
Note that if
is in lowercase letters. Uppercase letters (If or IF) will generate a JavaScript error.
Make a “Good day” greeting if the hour is less than 18:00:
<span style="color: mediumblue;">if</span> (hour < <span style="color: red;">18</span>) {
greeting = <span style="color: brown;">"Good day"</span>;
}
Use the else
statement to specify a block of code to be executed if the condition is false.
<span style="color: mediumblue;">if</span> (_condition_) {
<span style="color: green;">//</span>_ block of code to be executed if the condition is true_
} <span style="color: mediumblue;">else</span> {
<span style="color: green;">//</span>_ block of code to be executed if the condition is false_
}
If the hour is less than 18, create a "Good day" greeting, otherwise "Good evening":
<span style="color: mediumblue;">if</span> (hour < <span style="color: red;">18</span>) {
greeting = <span style="color: brown;">"Good day"</span>;
} <span style="color: mediumblue;">else</span> {
greeting = <span style="color: brown;">"Good evening"</span>;
}
#javascript #if else #html5 #css #js