Statement
Set of instructions is called a statement.
Conditional Statements
These statements will be executed when the condition given is met which means if the given condition is true then statements will get executed. If the condition is false, another statement will be executed.
In JavaScript we have following conditional statements :
- Use if to specify a block of code to be executed, if a specified condition is true
- Use else to specify a block of code to be executed, if the same condition is false
- Use else if to specify a new condition to test, if the first condition is false
- Use switch to select one of many blocks of code to be executed
Syntax of if conditional statement
Example :
In above example ‘a is true’ which means condition is met. So, code block will execute. If ‘a is false’ code block will not get execute as shown in below example.
Syntax of if else conditional statement
If you want to execute something when the condition is true and to execute something else when the condition is false then we can use if else conditional statement.
Example :
Syntax of if else if conditional statement
If you have multiple conditions to check then use if else if conditional statement.
Example :
switch
The switch statement contains multiple cases. A switch statement compares the value of the variable with multiple cases. If the value is matched with any of the cases, then the block of statements associated with this case will be executed.
For which each case, there will be one break which is used to come out of the loop.
This switch will have one default case which will be executed if no case is matched.
Syntax of switch conditional statement
Example :