Conditionals — If-Else vs Ternary Operator vs Switch-Case
Conditionals are part of the basics of every programming language. Conditionals are expressions that evaluate to either true or false. They are mostly used to determine Program Flow. Often times you will need to perform a particular action if a statement evaluates to true and another if it evaluates to false. To perform these actions we use conditionals.
NOTE : I am using JavaScript for the Code Snippets.
There are three common ways to use conditionals
- If-else statements
- Ternary operator
- Switch-Case
If-Else Statements
The if/else statement executes a block of code if a specified condition is true. If the condition is false, another block of code can be executed.
The if/else statement is a part of most programming languages “Conditional” Statements, which are used to perform different actions based on different conditions. Let’s look at some examples.
The else statement specifies a block of code to be executed 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
}