2

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?

3
  • 1
    It seems evident that c ? d : e must be a sub-expression (there's no other meaningful way to interpret those tokens). Therefore it really comes down to whether a && b ? x : y is (a && b) ? x : y or a && (b ? x : y). But surely this is solved with a trivial Google search for "javascript precedence" or similar? Commented Sep 17, 2014 at 23:31
  • 2
    Someone in jQuery should learn to use braces though it cost 2 bits in the framework size... Commented Sep 17, 2014 at 23:31
  • 1
    Also, the code format actually makes it easy in this case. Commented Sep 17, 2014 at 23:33

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, pony. You're a real pretty pony.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.