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.
That happens because the Boolean Operators in JavaScript can return an operand, and not necessarily a
Booleanresult, e.g.:The Logical AND operator (
&&), will return the value of the second operand if the first is truthy:And it will return the value of the first operand if it is by itself falsy:
That’s why in your example
"Huh?"is returned, because all the preceding expressions are truthy:The Logical OR operator (
||) has a similar behavior, it will return the value of the second operand, if the first one is falsy:And it will return the value of the first operand if it is by itself non-falsy:
This behavior is often used to set default values, for example:
Note: Falsy values are those that coerce to
falsewhen used in a boolean context, and they are:null,undefined,NaN,0, zero-length string, and of coursefalse. Anything else will coerce totrue.