Javascript if Statement Multiple Conditions
In this article, we will see about how to use multiple conditions in the javascript if statement. The conditional statements execute code based on the result of a given conditional expression. if, if else, else if ladder, and switch case are considered conditional or selections statements. We can use AND operator “&&” to achieve multiple conditions in the if statement.
if statement with multiple conditions
Syntax:
if( condition1 && condition2 && condition3 ... && conditionN)
{
statement; // statement executes only if all conditions are true
}
Example:
var a=10;
if( a%2==0 && a==10 && a>=10){
document.write("EVEN <br/>");
document.write("A is 10 <br/>");
document.write("GREATER THAN EQUAL TO 10");
}
Output:
Steps:
- In the above code, we have created a variable “a” and assigned the value “10“.
- Then we use the “if statement” with multiple conditions using the above syntax. We first check “a” variable has an even number then we check “a” variable has “10” and then we check “a” is greater than or equal to “10“.
- If the three conditions are true then inside the statement will be executed otherwise the statements won’t be executed.
- Here, three conditions are true, so the statement is displayed.
Conclusion
If you have used the AND operator in the if statement then the statements inside will execute only if all the conditions are true otherwise they will not execute. So you should use AND operator only where required.
If you have multiple conditions and you want to execute only if any of them is true, you can use the OR “||” operator.