Javascript Conditional Statements

You are currently viewing Javascript Conditional Statements

Javascript Conditional Statements

Conditional statements are used to execute different code blocks based on different conditions. If the condition meets then a particular block of action will be executed otherwise it will execute another block of action that satisfies that particular condition.
In JavaScript we have the following conditional statements:
1) if Statement
2) if-else Statement
3) if-else-if Statement
4) switch Statement

1) if Statement: The ‘if’ statement is used to execute a block of code only if a specified condition is true.If the condition is true, the code inside the if block is executed; otherwise, it is skipped.
Here’s the basic syntax:

				
					if (condition) {
  // Code to be executed if the condition is true
}

				
			

2) if-else Statement: The ‘if-else’ statement extends the if statement by providing an alternative block of code to execute if the condition is false. If the condition in the ‘if’ part is true, the code in the if block is executed. Otherwise, the code in the ‘else’ block is executed.
Here’s the syntax:

				
					if (condition) {
  // Code to be executed if the condition is true
} else {
  // Code to be executed if the condition is false
}

				
			

3) if-else-if Statement: This statement is used when you have multiple conditions to check in sequence. It allows us to handle different cases with different code blocks.
The conditions are checked one by one, and as soon as one of them evaluates to true, the corresponding code block is executed.
Here’s the syntax:

				
					if (condition1) {
  // Code to be executed if condition1 is true
} else if (condition2) {
  // Code to be executed if condition2 is true
} else {
  // Code to be executed if none of the conditions are true
}

				
			

4) Switch Statement: The switch statement is used to select one of many code blocks to be executed.
It’s particularly useful when we want to compare a single value against multiple possible values.
Here’s the syntax:

				
					switch (expression) {
  case value1:
    // Code to be executed if expression matches value1
    break;
  case value2:
    // Code to be executed if expression matches value2
    break;
  // More cases...
  default:
    // Code to be executed if expression doesn't match any case
}

				
			

Leave a Reply