Anjan Dutta

Multiple conditions in javascript if statement

Multiple conditions in javascript if statement

In programming, it is very common to get scenarios where we need to fulfil multiple conditions to establish a decision.

In this article, I am going to describe, how to use multiple conditions in javascript if statement.

Prerequisite

You should have basic programming knowledge in javascript to understand this concept.

Conditions are of 2 types logical AND (&&) and logical OR (||)

Logical AND (&&)

We use logical AND(&&) when all the conditions must be true to get a result.

Syntax

if (condition1 && condition2) {
// Execution block
}

below is an implementation of a scenario where:

  • A person aged greater than 18 years

    AND

  • A person of sex female

will be eligible for a license.

if (age > 18 && sex === 'F') {
grant_license = true;
}

Logical OR (||)

We use logical OR (||) when a minimum of one condition must be true to get a result.

Syntax

if (condition1 || condition2) {
// Execution block
}

below is an implementation of a scenario where:

  • A person aged greater than 60 years

    OR

  • A person with a disability

will be eligible for a pension.

if (age > 60 || disability === true) {
allow_pension = true;
}

Combining both

We can use a combination of both logical AND (&&) and logical OR (||) conditions. But it is suggested to use proper braces to make the conditions more meaningful.

Below is an implementation of a scenario where a bank will grant a loan to a customer only if the customer:

  • Credit score greater than 600 and age is less than 50

( credit_score > 600 && age <50 )

OR

  • Has a valid source of income.
  • Years of credit history greater than or equal to3
  • Age must be between 25 to 45
( source_of_income === true && credit_history_yrs >= 3 && ( age >= 25 && age <=45 ))

Combining both conditions:

if ( ( credit_score > 600 && age <50 ) ||
( source_of_income === true && credit_history_yrs >= 3 && ( age >= 25 && age <=45 ) ) ) {
grant_loan = true;
}

Operator precedence

Remember, logical AND (&&) has higher precedence than logical OR (||). Hence,

true || false && false // returns true, because && is executed first
(true || false) && false // returns false, because operator precedence defined using braces.

Thanks for reading my article.

Your feedback is valuable and encouraging.

Happy coding.