Mulan
Mulan

Reputation: 135396

How does JavaScript parse chained ternary expressions?

I'm reading through the jQuery source code for jQuery.filter and I stumbled upon this heaping pile of

jQuery.filter = function( expr, elems, not ) {
    var elem = elems[ 0 ];

    if ( not ) {
        expr = ":not(" + expr + ")";
    }

    return elems.length === 1 && elem.nodeType === 1 ?
        jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
        jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
            return elem.nodeType === 1;
        }));
};

So in short we have

return "a" && "b" ? "c" ? "d" : "e" : "f";

where each string could be a varying value

My question isn't how to decipher this code, but my brain is tying in knots trying to evaluate the logic being used here.

Can anyone help me understand how JavaScript evaluates this return expression?

Upvotes: 2

Views: 449

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 149050

The conditional operator is right-associative and the logical operators have higher precedence, so this:

return "a" && "b" ? "c" ? "d" : "e" : "f";

Is equivalent to this:

return ( ("a" && "b") ? ("c" ? "d" : "e") : "f" );

Or in full:

if ("a" && "b") {
    if ("c") {
        return "d";
    } else {
        return "e";
    }
} else {
    return "f";
}

Reference

Upvotes: 4

Related Questions