Home > Enterprise >  Expecting a Bool, Getting null
Expecting a Bool, Getting null

Time:04-02

I have a function in a class

MyClass.prototype.IsFriend = function(){
    return (this.m_Object1 && !this.m_Object1.m_ABoolean && this.m_Object2);
};

m_Object1 is an object in MyClass.

m_ABoolean is a boolean within m_Object1, true or false.

m_Object2 is another object in MyClass.

When this function should be returning false when m_Object1 is null OR m_ABoolean is true OR m_Object2 is null, it returns null instead.

Note: m_Object1, m_ABoolean and m_Object2 are never undefined.

Why?

CodePudding user response:

The && operator return the first falsy value (the operand itself) it encounters, if it encounters null it will return null -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND

CodePudding user response:

Logical operators in javascript return the first logically determined value from left to right,
For instance, && operator returns the first value if it's falsy or the second one if not.

This answer is a good read and the MDN Documentation is a good reference.

CodePudding user response:

I think that some of your values are null since:

true && null === null

Don't you have a way to check with debugger or with console.log the output of these values?

  • Related