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.
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.
Share Improve this question edited Apr 6, 2010 at 18:17 Jonas asked Apr 6, 2010 at 18:07 JonasJonas 4,5843 gold badges39 silver badges45 bronze badges 02 Answers
Reset to default 15That 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
.
&& and || don't neccesarily produce a boolean value.
https://developer.mozilla/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#logical_operators