-2

I'm facing a if condition issue in javascript. Please have look on below code.

1.

const a = 1;
if(a && a > -1)
{ 
console.log('suceess')
} 
else
{ 
console.log('failed')
}

Here in if condition it is returning true.

2.

const a = 0;
if(a && a > -1)
{ 
console.log('suceess')
} 
else
{ 
console.log('failed')
}

Here in if condition it is returning Zero.

I'm not getting this. Can someone please explain why is it so.

Mohit Swami
  • 125
  • 1
  • 1
  • 11

1 Answers1

1

in Javascript 0 is considered a "falsy" value, which mean il will be evaluate to false when used in a condition like if (0) {}.

See https://developer.mozilla.org/en-US/docs/Glossary/Falsy for more information about falsy values.

Christophe Le Besnerais
  • 3,895
  • 3
  • 24
  • 44
  • But here a is defined and a > -1 that is also true, Then why it is returning zero.? – Mohit Swami Mar 08 '22 at 15:06
  • `if (a)` doesn't check if `a` is defined... It checks whether the value referenced by `a` is truthy and, unfortunately, `0` is falsy so gets evaluated as false. – phuzi Mar 08 '22 at 15:08
  • 1
    a is defined but is equal to 0 which will evaluate to false, so if(0 && 0 > -1) will become if(false && true) which will evaluate to false – Christophe Le Besnerais Mar 08 '22 at 15:09
  • Is there any solution, how should I do my expected thing ? – Mohit Swami Mar 08 '22 at 15:11
  • what are you trying to check? That a is not empty and > -1 ? – Christophe Le Besnerais Mar 08 '22 at 15:17
  • It's yielding zero because of how the && operator works. If the first operand is falsy, that's what it yields. So (undefined && true) returns undefined, (0 && true) returns zero, (false && true) returns false. – James Mar 08 '22 at 15:29
  • @ChristopheLeBesnerais got the solution. I was trying to check a property of object if its exist and greater than -1 then assign from a another object esle assign a constant value. And I have found that we can use IN operator to check the property exist or not. Do you have any better idea about it ? – Mohit Swami Mar 08 '22 at 19:05
  • if you want to check that a is not null and not undefined you can use if (a != null) – Christophe Le Besnerais Mar 10 '22 at 08:56