Conditional Statements
The conditional statements are used to perform different actions for different decisions.
Just like any other languages, JavaScript has the following conditional statements:
- if for specifying a block of code to be executed, when a specified condition becomes true
- else to specify a block of code to be executed, when the condition is false
- else if (nested if) for specifying a new condition to test, when the first condition becomes false
The if Statement
Use the if statement to specify a block of JavaScript code to be executed when a condition becomes true.
Syntax of if statement
1 2 3 | if(condition){ block of code to be executed if the condition becomes true } |
Example
Make a “Good Morning” greeting if the hour is greater than 06:00:
1 2 3 | if(hour > 6){ greeting = "Good Morning"; } |
The if else Statement
Use of else statement for specifying a block of code to be executed when the condition becomes false.
Syntax of if else statement
1 2 3 4 5 6 | if(condition){ block of code to be executed if the condition becomes true } else{ block of code to be executed when the condition becomes false } |
Example of if else
If the hour is less than 12, create a “Good Morning” greeting, otherwise “Good Afternoon”:
1 2 3 4 5 6 | if(hour < 12){ greeting = "Good Morning"; } else{ greeting = "Good Afternoon"; } |
The else if Statement
Use else if statement to specify a new condition when the first condition is false.
Syntax
1 2 3 4 5 6 7 8 9 | if (condition1) { block of code to be executed if condition1 becomes true } else if (condition2) { block of code to be executed if the condition1 is false and condition2 becomes true } else { block of code to be executed when the condition1 is false and condition2 becomes false } |
Example of else if
If time is less than 12:00, create a “Good morning” greeting, if not, but time is less than 18:00, create a “Good day” greeting, otherwise a “Good evening”:
1 2 3 4 5 6 7 8 9 | if (time < 12) { greeting = "Good morning"; } else if (time < 18) { greeting = "Good day"; } else { greeting = "Good evening"; } |