Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS object null checking - weird JS problem [duplicate]

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 :)

like image 388
Tjodalv Avatar asked Dec 07 '25 18:12

Tjodalv


1 Answers

It's a common misconception. In JS (unlike in e.g. PHP) an expression like x && y does this:

  1. execute the expression x
  2. if the expression x 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).

like image 172
Nurbol Alpysbayev Avatar answered Dec 09 '25 07:12

Nurbol Alpysbayev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!