-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.

7
  • 1
    why do you check for a? what result do you expect? Commented Mar 8, 2022 at 15:00
  • @Gereon No. I didn't get. Commented Mar 8, 2022 at 15:02
  • @NinaScholz, I'm expecting that if a = 0 , then condition should be true. Commented Mar 8, 2022 at 15:03
  • If a = 0 then in if(a && a > -1) the first check becomes false. It's just like having if (false &&... and the second part of the if isn't even checked Commented Mar 8, 2022 at 15:05
  • 0 is a falsey value and will be evaluated as false rendering the whole condition false. (a > -1 never gets evaluated due to short-circuit evaluation) Commented Mar 8, 2022 at 15:05

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

8 Comments

But here a is defined and a > -1 that is also true, Then why it is returning zero.?
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.
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
Is there any solution, how should I do my expected thing ?
what are you trying to check? That a is not empty and > -1 ?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.