tags:

views:

68

answers:

2

I ran across this chunk of code (modified) in our application, and am confused to how it works:

    function someObject()
    {
        this.someProperty = {};
        this.foo = 
        {
            bar:
            {
                baz: function() { return "Huh?" }
            }
        };

        this.getValue = function()
        {
            return (this.someProperty && this.foo.bar && this.foo.bar.baz && this.foo.bar.baz()) || null;
        }
    }

    function test()
    {
        var o = new someObject();
        var val = o.getValue();
        alert(val);
    }

when you call the test() function, the text "Huh?" is alerted. I'm not sure how the result of getValue is returning that, I would've thought doing A && B && C && D would have returned true, rather than the value of D.

+8  A: 

That happens because the Boolean Operators in JavaScript can return an operand, and not necessarily a Boolean result, e.g.:

The Logical AND operator (&&), will return the value of the second operand if the first is truthy:

true && "foo"; // "foo"

And it will return the value of the first operand if it is by itself falsy:

NaN && "anything"; // NaN
0 && "anything";   // 0

That's why in your example "Huh?" is returned, because all the preceding expressions are truthy:

alert("A" && "B" && "C" && "Huh?"); // "Huh?"
alert(true && true && true && "Huh?"); // "Huh?"

The Logical OR operator (||) has a similar behavior, it will return the value of the second operand, if the first one is falsy:

false || "bar"; // "bar"

And it will return the value of the first operand if it is by itself non-falsy:

"foo" || "anything"; // "foo"

This behavior is often used to set default values, for example:

function test (arg1) {
  arg1 = arg1 || "default value";
}

Note: Falsy values are those that coerce to false when used in a boolean context, and they are: null, undefined, NaN, 0, zero-length string, and of course false. Anything else will coerce to true.

CMS
David Murdoch
On a related note, the existence of this question here is evidence that using these boolean syntactic shortcuts for logic should be considered bad form... "Say what you mean", said the March Hare.
dkamins
Excellent summary of javascripts often misunderstood operators!
Mike Clark
+1  A: 

&& and || don't neccesarily produce a boolean value.

https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Operators/Logical_Operators

chris
I was just about to add that as a comment. :) Thanks!
Jonas