JavaScript conditional statements allow you to make decisions in your code based on whether a certain condition is true or false. The two most commonly used conditional statements in JavaScript are if
and else
.
Using an if
statement in JavaScript:
The curly braces code will only be executed if the condition x > 5
is true.
let x = 10;
if (x > 5) {
console.log("x is greater than 5");
}
Use an else
statement to specify what should happen if the condition is false:
Since the condition x > 5
is false, the code inside the else
block will be executed instead.
let x = 8;
if (x > 10) {
console.log("x is greater than 10");
} else if (x > 5) {
console.log("x is greater than 5 but less than or equal to 10");
} else {
console.log("x is less than or equal to 5");
}
JavaScript conditional statement example
Simple example code of JavaScript Conditional Statement using If-Else Statement.
<!DOCTYPE html>
<html>
<body>
<script>
let number = -5;
if (number > 0) {
console.log("The number is positive");
} else if (number < 0) {
console.log("The number is negative");
} else {
console.log("The number is zero");
}
</script>
</body>
</html>
Output:
Do comment if you have any doubts or suggestions on this JS basic topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version