Imagine this simple scenario. I have variable that can be plain JS object with one property, ID, that is a number or obj variable can be null. I have simple test() function that checks if the variable is not null and that it must have valid id property.
var obj = { id: 111 };
function test() {
return (obj && obj.id);
}
I am expecting that this function will always return boolean but in fact it returns undefined if the obj is undefined or value of obj.id if object exists like in case above. Why this function return 111 instead of true.
I am going to rip off hair of my head ... Please illuminate my mind :)
It's a common misconception. In JS (unlike in e.g. PHP) an expression like x && y does this:
xx returned true, then execute the expression y as well and return it (y). Otherwise return x (which would be falsy in this case e.g. 0, '', false, null, undefined).In other words it works more like a ternary expression x ? y : z.
If you want a boolean, then use !!(x && y).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With