JS object null checking - weird JS problem [duplicate]

谁都会走 提交于 2019-12-10 21:37:56

问题


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


回答1:


When obj is defined, why does if (obj && obj.id) return 111?

The logical AND (&&) operator returns expr1 if it can be converted to false; otherwise, returns expr2.

MDN: Logical Operators - Description (slightly paraphrased)

expr1 (obj) cannot be converted to false, therefore it returns expr2 (111).


Why does it not return true?

Logical operators are typically used with Boolean (logical) values. When they are, they return a Boolean value. However, the && and || actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value.

MDN: Logical Operators

Because you are using the logical operator with non-Boolean values, the result will be non-Boolean as well.




回答2:


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



来源:https://stackoverflow.com/questions/53597233/js-object-null-checking-weird-js-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!