How to Use AND Statement in if with JavaScript?
In JavaScript AND (&&) logical operator is used in the 'if' statement to check for two or more conditional validities. AND logical operator in the 'if' condition returns true only when all the conditions inside the 'if' statement are TRUE. If any one condition inside the 'if' statement is FALSE, then the entire 'if' statement condition becomes FALSE, and hence, the 'if' block doesn't execute in this case. We usually use the AND logical operator with an if statement, if we want all the conditions mentioned inside the 'if' statement to be exhaustive.
When the 'if' statement has multiple AND conditions
In this, the ' if ' statement can include two or more conditions to satisfy exhaustively for the 'if' block to execute. Here, even if one condition fails the entire 'if' statement fails and the 'if' block does not get executed. This behavior of the && operator with it is because of how logical AND operator works in general.
Syntax:
if (condition1 && condition2 && /* more conditions */) {
// This block gets executed only if all conditions are TRUE.
}
Example 1: This example code implements the above approach, here the if block only executes if both of the two mentioned conditions inside the if statement are true.
const gfgUser = true;
const isPremiumMember = true;
if (gfgUser && isPremiumMember)
console.log(`You'll get an opportunity to learn a lot with premium features`);
Output
You'll get an opportunity to learn a lot with premium features
Example 2: This example code implements the above approach, here the 'if' block only executes if all the mentioned conditions inside the 'if' statement are true.
const gfgUser = true;
const isPremiumMember = true;
const hasCompletedCourses = true;
if (gfgUser && isPremiumMember && hasCompletedCourses)
console.log(`You are a premium user who has completed courses.`);
Output
You are a premium user who has completed courses.