Javascript Conditional Statements
Conditional statements are used to execute certain code based on certain conditions. The if statement is used to execute code if a condition is true.
If statement
The if statement is used to execute code if a condition is true. In this case, the code inside the curly braces will be executed because num is greater than 0.
Here's an example of If statement in JavaScript
// if Statement
let num = 5;
if (num > 0) {
alert("The number is positive.");
}
If-else statement in Javascript
The if-else statement is used to execute one block of code if a condition is true and another block of code if the condition is false. In this case, the code inside the first set of curly braces will not be executed, and the code inside the second set of curly braces will be executed instead.
Here's an example of if-else in JavaScript
// if-else
let num = -5;
if (num > 0) {
alert("The number is positive.");
} else{
alert("The number is negative.");
}
If-else-if-else in JavaScript
The if-else-if-else statement is used to execute different blocks of code based on different conditions. In this case, the code inside the third set of curly braces will be executed because num is equal to 0.
Here's an example code on of if-else-if-else statement in JavaScript
// if-else-if-else
let num = 0;
if (num > 0) {
alert("The number is positive.");
}
else if (num < 0) {
alert("The number is negative.");
}
else {
alert("The number is zero.");
}
Nested if-else-if-else statement in JavaScript
The nested if-else-if-else statement is used when we need to check more than one condition in a specific block of code. In this case, we have one if statement nested within another if statement.
In this case, the code inside the first set of curly braces will be executed because num is greater than 0. The nested if-else statement will then check whether num is even or odd, and execute the appropriate code.
Here's an example code of nested if-else-if-else statement in JavaScript
// nested if-else-if-else
let num = 10;
if (num > 0) {
if (num % 2 == 0) {
alert("The number is positive and even.");
} else {
alert("The number is positive and odd.");
}
} else if (num < 0) {
alert("The number is negative.");
} else {
alert("The number is zero.");
}
};
Conclusion
Overall, conditional statement is a structure that allows the execution of a particular set of code depending on whether a certain condition is true or false. The most common example of a condition statement is the if statement, which evaluates a Boolean expression and executes a block of code if the expression is true.
Now challenge yourself, click the link below to practice!