Hey guys i was just going through the source of a JS plugin (dropdown.js) and came across the following line of code:
return $parent && $parent.length ? $parent : $this.parent()
I am not able to grasp the above line completely, I understand Logical And (&&) and the Ternary Conditional Operator (... ? ... : ...
), but I don't seem to comprehend how they interact in the above example.
Now if I add a console.log
before the return
statement:
console.log($parent && $parent.length ? $parent : $this.parent());
I get:
Object { 0: <li.dropdown.open>, length: 1, prevObject: Object, context: <a.dropdown-toggle>, selector: ".parent()" }
Which indeed is $this.parent()
Also, $parent
in my case evaluates to false
.
So these are the Lego pieces I have, can somebody put it in place for me and give me a clear picture of how this works:
return $parent && $parent.length ? $parent : $this.parent()
Thank you.
Due to JavaScript's operator precedence, the expression you posted is equivalent to:
return ($parent && $parent.length) ? $parent : $this.parent();
This is due to the &&
operator being evaluated before ?:
. Alternatively, you can rewrite the expression using if else
:
if ($parent && $parent.length)
return $parent;
else
return $this.parent();