Conditional statements are used in programming to used execute specific code based on certain conditions. In JavaScript, if else execute based on the return value of the conditional statement.
The If-Else Statement
syntax:
if (condition) {
// execute this block of code if condition is true
} else {
// execute this block of code if condition is false
}
Here, condition
is an expression that evaluates to either true
or false
. If condition
is true
, the code inside the first set of curly braces will be executed. If condition
is false
, the code inside the second set of curly braces will be executed.
Example:
let score = 40;
if (age >= 40) {
console.log("You scored above 40");
} else {
console.log("You scored below 40");
}
In this example, if score
is greater than or equal to 40
, the message "You scored above 40" will be printed to the console. If score
is less than 40
, the message "You scored below 40" will be printed.
The If-Else If Statement
The if-else if
statement can be used when there are multiple conditions that need to be evaluated.
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 all conditions are false
}
Here, if condition1
is true
, the code inside the first set of curly braces will be executed. If condition1
is false
and condition2
is true
, the code inside the second set of curly braces will be executed. If both condition1
and condition2
are false
, the code inside the third set of curly braces will be executed.
Example:
let volt = 150;
if (volt >= 200) {
console.log("Voltage above 200");
} else if (volt >= 175) {
console.log("Voltage above 175");
} else if (volt >= 150) {
console.log("Voltage above 150");
} else if (volt >= 100) {
console.log("Voltage above 100");
} else {
console.log("Voltage below 100");
}
In this example, while check the volt value in if else if
statement third one is valid, Voltage above 150
will be printed in the console. Condition below the statement are valid but it won't execute because the one if statement is already valid.
Top comments (0)