In JavaScript, you can use an if/else
statement to control the flow of your program based on a condition.
Here’s an example of a simple if/else
statement in JavaScript:
let x = 10;
if (x > 5) {
console.log("x is greater than 5");
} else {
console.log("x is less than or equal to 5");
}
In this example, the condition x > 5
is evaluated, and the appropriate block of code (either the if
block or the else
block) is executed based on the result of the evaluation. In this case, x
is 10
, so the condition x > 5
is true, and the message “x is greater than 5” is logged to the console.
You can also chain multiple if/else
statements together to create more complex conditionals:
let x = 10;
if (x > 15) {
console.log("x is greater than 15");
} else if (x > 10) {
console.log("x is greater than 10 but less than or equal to 15");
} else {
console.log("x is less than or equal to 10");
}
In this example, there are two conditions (x > 15
and x > 10
), and the appropriate block of code is executed based on the result of each evaluation. In this case, x
is 10
, so the condition x > 15
is false, the condition x > 10
is true, and the message “x is greater than 10 but less than or equal to 15” is logged to the console.
+ There are no comments
Add yours