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.
The easiest way to merge two objects in JavaScript is with the ES6 spread syntax / operator ( ... ). All you have to do is insert one object into another object along with the spread syntax and any object you use the spread syntax on will be merged into the parent object.
To merge objects into a new one that has all properties of the merged objects, you have two options: Use a spread operator ( ... ) Use the Object. assign() method.
Description. Logical AND ( && ) evaluates operands from left to right, returning immediately with the value of the first falsy operand it encounters; if all values are truthy, the value of the last operand is returned. If a value can be converted to true , the value is so-called truthy.
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
.
&& and || don't neccesarily produce a boolean value.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#logical_operators
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With