JavaScript if multiple conditions | Example code

  • by

Use either “&&” or “||” i.e. logical AND or logical OR operator to connect two or multiple conditions inside a if statement in JavaScript. Multiple expression in if conditions is used to narrow down result.

AND: &&

// If x is 3 and y is 5 if(x == 3 && y == 5){ ... } 

OR: ||

// If x is 3 or y is 5 if(x == 3 || y == 5){ ... } 

JavaScript if multiple conditions

Simple example code to find the number which is divisible by both 5 and 7 ,using logical AND, which returns true only if both the conditions are true.

<!DOCTYPE html>
<html>
<body>
  <script>
    var x = 70;

    if(x%5 == 0 && x% 7== 0){ 
      console.log(" X divided by both 5 and 7");
    }
  </script>
  
</body>
</html

Output:

JavaScript if multiple conditions

If you need to find out, is the number divisible by either 5 or 7? You need to use logical OR ,

<script>
    var x = 70;

    if(x%5==0 || x%7 ==0){ 
      console.log(" X divided by 5 OR 7");
    }
</script>

Truth table for AND operator:

ABA && B
TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse

Example: Same example can done with or operator.

var arr = [5,25,70,62,20,89];

arr.forEach(num => {
    if (num == 20 && num%2 == 0){
    console.log(num);
}  
})

Using AND and OR Operators in Combination Inside the if Statement in JavaScript

var arr = [5,25,70,62,20,89];

arr.forEach(num => {
  	if ( (num != 20 && num%2 == 0) || (num > 50) && (num < 100)){
    	console.log(num);
	}  
})

Output:

70
62
89

Do comment if you have any doubts or suggestions on this JS if code.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.