I came across the use of the logical operand && with objects however would like to know whether expressions are evaluated in the manner below only when dealing with objects.
Code Sample
var sampleObject = {
size: 10,
shoe: {
make: "nike",
model: "air jordon"
},
color: "red"
}
console.log(sampleObject.size && sampleObject.shoe.model);
The out of console.log(sampleObject.size && sampleObject.shoe.model); returns air jordon. My understanding is that because the first condition i.e. sampleObject.size evaluated to true and isn’t falsely it returns the value contained in the object sampleObbject.shoe.model.
The
||and&&operators run from left to right. In the case of||, the first truthy value is returned. For&&, it’s the first falsy value. In both cases, the last one is returned if no suitable return value is found.So, in this case, the fact that it returned a truthy value for the expression means that both
sampleObject.sizeandsampleObject.show.modelare truthy values.