Conditional statements
Conditional Statements, as the name suggests, only execute a statement, or a bunch of statements only if a condition is true.
Before learning about the different types of Conditional statements, let's have a look at some, not so frequently used, terms.
- Condition: An expression whose value is considered as a condition.
- ExprIfTrue: An expression that is executed if the condition is Truthy.
- ExprIfFalse: An expression that is executed if the condition is Falsy
Posts on Truth and Falsy values coming soon~
Ways to implement Conditional Statements in JavaScript
To make use of Conditional statements, we need to use the operators provided in JavaScript, or, if we don't use any operator but just a variable, The condition will be considered true if the variable provided is anything accepted being a falsy value.
If statements
"If statements" are the most frequently used Conditional statements in JavaScript.
It has a very simple, elegant, function-like, and self-explanatory syntax. We just need to use the "if" keyword instead of "function".
let hour = 5
if (hour < 12) {
console.log("It's not afternoon yet.")
}
What if we have more than 1 condition?
For that we have:
If-else statements
They are very similar to if statements and in fact can only be used once a statement is started.
We use the "else" keyword to provide another "if" condition or we can simply use the "else" keyword to provide a statement that will only execute if none of the provided statements were true.
Let's learn to write "If-else" Statements by writing a program to determine whether a number is odd or even.
let num = 5
if (num % 2 === 0){
console. log(`${num} is even`)
}
else console. log(`${num} is odd`)
Here we used the modulus operator than returns the remainder when the first operand is divided by the second, in this case, the remainder when 5 is divided by 2 is not 0, so it moves to the next else statement and prints that it's odd.
Switch Case Statements
switch(expression) {
case x:
// some code
break;
// some code
case y:
// some code
break;
default:
// some code
}
- The switch expression is evaluated once.
- The value of the expression is compared with the values of each case.
- If there is a match, the associated block of code is executed.
- If there is no match, the default code block is Executed
Ternary Operator
The Ternary Operator can be considered a short-hand method to writing if statements, it's used in the following way:
condition? ExprIfTrue: ExprIfFalse
Hope you learned something useful today! Peace Out ✌️
Top comments (0)