0

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?

Rewind
  • 2,554
  • 3
  • 30
  • 56
  • Can you edit your question to include a reproducible example as a stack snippet? – Wyck Apr 01 '22 at 18:01
  • 1
    The operator (`&&`) returns the value of the *first* falsy operand encountered when evaluating from left to right, or the value of the *last* operand if they are all truthy. – dokgu Apr 01 '22 at 18:04

3 Answers3

2

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

Prince Agrawal
  • 380
  • 4
  • 14
  • 1
    This is the answer, because it returns `null` when `m_Object1` is null. I never knew this. I always throught a logic statement with a load of `&&` would return a boolean. What is the recognised convention to use to get the funtion working as I want, maybe `return (!!this.m_Object1 && !this.m_Object1.m_ABoolean && !!this.m_Object2)` – Rewind Apr 01 '22 at 18:05
  • 1
    @Rewind you could also just check for null values: `this.m_Object1 != null`. – dokgu Apr 01 '22 at 18:06
  • Would `!!obj` be just as good to limit characters to minimize javascript file size? – Rewind Apr 01 '22 at 18:08
  • 1
    @Rewind using !! will work in your use case – Prince Agrawal Apr 01 '22 at 18:10
  • 1
    JavaScript curiosities: `!!{}` is true but `!!document.all` is false. [reason](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) – Wyck Apr 01 '22 at 18:18
1

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.

chandresh_n
  • 473
  • 2
  • 4
0

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?

Fer Toasted
  • 1,274
  • 1
  • 11
  • 27