Skip to content
Related Articles

Related Articles

Improve Article

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

  • Last Updated : 19 Jul, 2021

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

|| (Or) Operator: The ‘OR’ operator is 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 0In 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
Recommended Articles
Page :