Why does ‘false or null’ return null, but ‘true or null’ returns true?

0
6
Asked By CuriousCoder42 On

I'm trying to understand boolean values better, and I'm confused about why 'false or null' evaluates to null, while 'true or null' evaluates to true. Wouldn't they both evaluate as false? It's really puzzling! I appreciate any help you can provide. Also, I've already googled this, but I couldn't find a clear explanation because the results were more about null being equal to false or true, which isn't what I'm asking about. Thanks!

4 Answers

Answered By TechieNerd99 On

This is all about short-circuit evaluation. In the expression 'true or null', the evaluation stops at 'true' since it doesn’t need to check any further. However, in 'false or null', it checks both sides because the left is false, resulting in null. So, the key point is that 'or' will stop evaluating once it finds a true value, hence 'true or null' gives you true.

Answered By CodeWizard21 On

This kind of behavior can vary between programming languages. In JavaScript, for instance, 'false || null' returns null because 'false' is falsy, so it moves on to the next value, which is null. Conversely, 'true || null' returns true because 'true' is already a valid truthy value. It’s definitely worth looking into the concepts of truthy and falsy values in your language!

Answered By DebuggerDude13 On

You're right that null is often treated differently from boolean values across languages. Typically, 'or' operations return the first truthy value or the last one if none are truthy. In your example, 'false or null' evaluates to null because both are falsy, while 'true or null' evaluates to true since true is truthy.

Answered By LogicLover88 On

Have you looked into how the 'or' operator works? Generally, if the first value is truthy, it returns that without checking the second. So with 'true or null', it returns true right away. But with 'false or null', it sees 'false', checks 'null', and ends up with null, since both are falsy just like you suspected.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.