Search code examples
javascriptminify

When reading minified Javascript, how am I supposed to read this return statement with commas, &&, and || operators?


I have this source code:

function findMessageErrors(btn) {
    var error = "";
    var message = $(btn).parent().siblings().find("textarea[name='message']").val();
    if (message === "") {
        error += "*Please enter a message.<br/>";
    }
    if (!$(btn).parent().siblings().find('input[name="agree"]').prop('checked')) {
        error += "*Please agree.<br/>";
    }
    return error;
}

This gets minified. After minification, it looks like this in the Chrome Dev tools Sources tab:

function findMessageErrors(btn) {
    var error = "";
    return "" === $(btn).parent().siblings().find("textarea[name='message']").val() && (error += "*Please enter a message.<br/>"),
    $(btn).parent().siblings().find('input[name="agree"]').prop("checked") || (error += "*Please agree.<br/>"),
    error
}

I understand how the comma operator 'runs a series of expressions, in order, and then returns the result of the last of them' (from here). But I'm having a hard time understanding how those OR and AND operators are working in building that string that gets returned in the minified code.

Does anyone have a helpful way of reading that out loud that will help me understand how that works? I guess I don't see how 2 independent IF statements in the source gets minified into a series of && then ||. I don't want to have to look up the source every time I want to understand the logic of how the minified code works.


Solution

  • Where possible, use source maps rather than trying to read minified code.

    But that doesn't mean you don't want to know how to read complex statements; sometimes humans write them. :-)

    I've done some formatting and inline comments to explain:

    function findMessageErrors(btn) {
        var error = "";
        return (
            (
                "" === $(btn).parent().siblings().find("textarea[name='message']").val()
                &&
                // This only runs if the === above is true, because of the &&
                (error += "*Please enter a message.<br/>")
            )
            ,
            ( // This runs regardless of the above
                $(btn).parent().siblings().find('input[name="agree"]').prop("checked")
                ||
                // This only runs if prop("checked") returned a falsy value, because of ||
                (error += "*Please agree.<br/>")
            )
            ,
            ( // This runs regardless, of the above...
                // ...and this is the ultimate value of the return
                error
            )
        );
    }
    

    The outer () are just added because a linebreak after return triggers (the horror that is) automatic semicolon insertion. Other () are added for clarity of explanation.