Conditional statements are used to decide the flow of execution based on different conditions. If a condition is true, you can perform one action and if the condition is false, you can perform another action.
Different Types of Conditional Statements
There are mainly three types of conditional statements in JavaScript.
- If statement
- If…Else statement
- If…Else If…Else statement
If statement
Syntax:
1
2
3
4
5
6
7
| if (condition) { lines of code to be executed if condition is true } |
You can use If statement if you want to check only a specific condition.
Try this yourself:
If…Else statement
Syntax:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| if (condition) { lines of code to be executed if the condition is true } else { lines of code to be executed if the condition is false } |
You can use If….Else statement if you have to check two conditions and execute different set of codes.
Try this yourself:
If…Else If…Else statement
Syntax:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
| if (condition1) { lines of code to be executed if condition1 is true } else if (condition2) { lines of code to be executed if condition2 is true } else { lines of code to be executed if condition1 is false and condition2 is false } |
You can use If….Else If….Else statement if you want to check more than two conditions.
Try this yourself: