Skip to content

JavaScript if statement multiple conditions | Example code

  • by

Use And (&&) or OR (||) statement to get the if statement with multiple conditions in JavaScript. Just make sure you wrap your conditions in parentheses required to evaluate in the order that you want them evaluated.

Here is a couple of option depending on what you are up to gain:

    && - and 
    // if conditions 1 and 2 are true do something  
    If (cond1 && cond2) { 
       Do something  
    }  
     
    || - or  
    // if conditions 1 or 2 are true do something  
    If (cond1 || cond2) { 
       Do something  
    }  
    ! == - not 
    // if conditions 1 is not equal  to 2  do something  
    If (cond1!== cond2) { 
       Do something  
    }  

Multiple conditions are just a boolean expression:

if (condition1 && condition2 || condition3) { ... } 

JavaScript if statement multiple conditions

A simple example code to check a given number is divisible by 5 and 7.

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

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

Output:

JavaScript if statement multiple conditions

OR

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

if(x%5==0 || x%7 ==0){ 
    // code
}

Do comment if you have any doubts or suggestions on this Js if statement topic.

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

OS: Windows 10

Code: HTML 5 Version

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *