Search code examples
javascriptjquerysmarty

Shorthand/implicit if() statement with no if


JavaScript/jQuery code found in a Smarty template:

( $( 'carriercode' ) && $( 'carriercode' ).value == '' )
{
    alert( 'Please select Shipping Carrier Code' );
    return false;
}

This isn't so much a problem as a curiosity.

Question 1: I've never seen this construction before. It appears to work exactly like an if() statement, but without the if keyword. Is this valid/standard/reliably supported?

Question 2: the jQuery selector is looking for the carriercode tag, which obviously isn't part of standard HTML. Is this a feature of Smarty, or just lazy developers making up new tags? Again, is it valid (in Smarty), standard practice, and will it work reliably?

Related: I did a minimal test in a simple HTML page (below), which works but isn't valid markup. I'm curious whether it would work reliably in different environments. I always follow standards when writing my own code, but sometimes it's not practical to go in and fix up all the code when joining an existing project.

<!doctype html>
<html lang='en-gb'>
    <head>
        <meta charset='utf-8' />
        <title>Test</title>
        <script src="https://code.jquery.com/jquery-1.11.3.js"></script>
        <script>
            //<![CDATA[
            ( $( 'test' ) && $( 'test' ).value === 'test' )
            {
                alert( 'test!' );
            }
            //]]>
        </script>
    </head>
    <body>
        <h1>Test</h1>
        <p>Test</p>
        <test value='test'></test>
    </body>
</html>

I've been unable to find out much about either of these questions by searching the internet, searching for if tends to return a lot of results about JavaScript for beginners which might be swamping answers to more esoteric cases like this. Thanks in advance for any insight!


Solution

  • Summarising the helpful answers that were provided in comments, plus a bit more info:

    1. Omitting the if on the conditional statement just means that the result is thrown away after evaluation. In other words, this is a bug.

    2. Confusingly, the codebase where I found this code uses both jQuery and Prototype.js, both of which use the $() construct by default. $( 'test' ) && $( 'test' ).value === 'test' is valid Prototype.js, and it's looking for an element with an id of #test. This is by contrast to jQuery, where to look for an id it must be prefixed by # in the selector. In fact this codebase was using jQuery's noConflict() to avoid use of $() because it would interfere with Prototype.js.

    3. jQuery selectors work on any element name, not just ones that are valid in HTML.

    4. I should do more testing before asking questions. Thanks again to the commenters for their help and patience!