Often, when writing code, you need to take different actions based on various decisions.
You can achieve this using conditional statements.
In JavaScript, the following conditional statements are available:
if
to define a block of code that runs if a specified condition is true.else
to define a block of code that runs if the same condition is false.else if
to test a new condition if the first one is false.switch
to define multiple alternative blocks of code to execute.The switch statement will be covered in the next chapter. |
Use the if statement to define a block of JavaScript code that should be executed when a condition is true.
if (condition) { // block of code to be executed if the condition is true } |
Keep in mind that “if” should be in lowercase; using uppercase letters (If or IF) will result in a JavaScript error. |
Create a “Good day” greeting if the hour is before 18:00.
if (hour < 18) { greeting = “Good day”; } |
The outcome of the greeting will be:
Good day |
Use the else statement to define a block of code that should run if the condition is false.
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 } |
If the hour is before 18, display a “Good day” greeting; otherwise, show “Good evening.”
if (hour < 18) { greeting = “Good day”; } else { greeting = “Good evening”; } |
The resulting greeting will be:
Good day |
Use the else if statement to define a new condition to test if the initial condition is false.
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 } |
If the time is before 10:00, display a “Good morning” greeting; if not, but the time is before 20:00, show a “Good day” greeting; otherwise, display “Good evening.”
if (time < 10) { greeting = “Good morning”; } else if (time < 20) { greeting = “Good day”; } else { greeting = “Good evening”; } |
The resulting greeting will be:
Good day |