Ternary statement [was Re: [Javascript] Show and hide multiple div tags]

liorean liorean at gmail.com
Sat May 13 14:42:50 CDT 2006


On 13/05/06, Triche Osborne <wdlists at triche-osborne.com>
> The point was that it has to be part of a completed statement--that is,
> the returned results must be used in some way.

No, they don't. Expressions may be Statements in and of themselves if
they appear as ExpressionStatements. The difference is that then the
return value is automatically discarded.

> In both of your examples above, this is what's happening: In the first,
> the result is assigned to document.getElementById('someID').title; in
> the second, it determines which text is appended to span.appendChild.

True... but those were bad examples.

> Neither this . . .
>
> navigator.platform == 'MacPPC'
>  >       ? 'command click to do some stuff'
>  >       : 'ctrl click to do some stuff';
>
> NOR this . . .
>
>  >       someNumber < someOtherNumber
>  >       ? document.createTextNode('some text')
>  >       : document.createTextNode('some other text')
>
> form a complete statement in and of themselves.

Wrong. They are both fully valid ExpressionStatements, and thereby
they do form complete statements. They are pointless since they
discard the return value, but they are complete statements.

Let's try at an example which uses side effects instead:

    'body' in document?
        document.body.appendChild(
            document.createTextNode('document.body property exists,
which in all probability means the document is HTML')):
        document.documentElement.appendChild(
            document.createTextNode('document.body property doesn't
exist, which in all probability means the document is either plain XML
or XHTML'));

Return value might be discarded, but the expression is a statement in
and of it's own, and will have side effects on the DOM.




Oh, and just for the record: "ternary operator" means
operator-with-three-operands. The name of this specific operator is
the "conditional operator". It just happens to be the only ternary
operator in ECMAScript. You don't go around calling "--" for the
"unary operator" or "instanceof" (just to grab a totally ridiculous
example) for the "binary operator", do you?
Unary, binary or ternary just explains how many operands they have,
the important thing is their functionality.
-- 
David "liorean" Andersson
<uri:http://liorean.web-graphics.com/>



More information about the Javascript mailing list