Why does 'false or null' return null, but 'true or null' returns true?
Asked by
CuriousCoder42
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!
Answers
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.
Reply to this answer
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.
Reply to this answer
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!
Reply to this answer
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.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Related Discussions