How to use Conditional Statement
Describes how to use conditional statements in JavaScript.
JavaScript can use conditional branching in many ways. This article describes the commonly used if and switch statements.
if / else / else if
const point = 9;
// if statement
if (point < 10) {
console.log("Point is smaller than 10"); // execute
}
if (point > 10) {
console.log("Point is bigger than 10"); // not execute
}
// else statement
if (point > 10) {
console.log("Point is bigger than 10"); // not execute
} else {
console.log("Point is same of smaller than 10"); // execute
}
// else if statement
if (point > 10) {
console.log("Point is bigger than 10"); // not execute
} else if (point > 5) {
console.log("Point is bigger than 5"); // execute
} else {
console.log("Point is same of smaller than 10"); // execute
}
For else , if, you can also add more than one.
if (point > 10) {
console.log("Point is bigger than 10");
} else if (point > 7) {
console.log("Point is bigger than 7");
} else if (point > 3) {
console.log("Point is bigger than 3");
} else {
console.log("Point is same of smaller than 10");
}
switch - case
If you need to evaluate multiple conditions, using a switch statement may be more effective than using an elseif statement repeatedly. The switch statement starts with the switch keyword and evaluates the condition with the case keyword. Each case keyword must contain the break keyword to stop executing the switch statement.
const color = "red";
switch (color) {
case "blue":
console.log("Color is blue!");
break;
case "red":
console.log("Color is red!");
break;
default:
console.log("Color is not blue or red!");
}