Skip to content
Related Articles
Open in App
Not now

Related Articles

Difference between a || b < 0 and a < 0 || b < 0 in JavaScript ?

Improve Article
Save Article
  • Last Updated : 09 Jan, 2023
Improve Article
Save Article

Both expression almost looks the same when we focused on the || (Or) operator, but both expressions are different from each other. To know the final conclusion, we have to get the knowledge of the || (Or) operator first.

JavaScript || (Or) Operator: The ‘OR’ operator is the opposite of the ‘AND’ operator. It does evaluate the operand from left to right. For each operand, it will first convert it to a boolean. If the result is true, it stops and returns the original value of that operand. Otherwise, if all the values are false, it will return the last value.

For in-depth content about other Logical Operators in JavaScript, you can check JavaScript Course Logical Operators in JavaScript

Expression 1: 

a < 0 || b < 0

Example: The expression a < 0 || b < 0 gets evaluated and if it’s not a boolean, it’s coerced to one. Both ‘a’ and ‘b’ get compared with 0.

Javascript




<script>
    function myFunction(a, b) {
       
    if (a < 0 || b < 0) {
      console.log("The value of a and b "+ a, b);
      }else{
      console.log("GFG")
    }
    }
    myFunction(2,5);
</script>


Output:

GFG

Expression 2: 

a || b < 0

Example: The expression gets evaluated and if it’s not a boolean, it’s coerced to one. The value of ‘a’ gets compared not the ‘b’.

Javascript




<script>
    function myFunction(a, b) {
       
    if (a || b < 0) {
      console.log("The value of a and b "+ a, b);
      }else{
      console.log("GFG")
    }
    }
    myFunction(2,5);
</script>


Output:

The value of a and b 
2
5

Difference between a || b < 0 and a < 0 || b < 0:

a || b < 0

a < 0 || b < 0

In this expression, the value of a will get compared with the 0 In this expression, the a and b both will get compared with the 0
This is a less used or useless kind of expression. This is the most used expression to compare two variables.

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!