Search code examples
javascriptoperator-precedence

Operator Precedence with Ternary Conditional and Logical And operators in JavaScript


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.


*Please note that the pre-edit version of this question had an incorrect title and didn't explain what the question really was until one looked at it with sufficient care, therefore please don't downvote any answers below that may seem to talk about "Short-circuiting" in place of the actual topic of this question (Operator Precedence) for the sole sake of looking out-of-topic and careless


Solution

  • 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();