simple code not working

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Richard Barnet

    simple code not working

    Why doesn't this work?:



    var backlink = readCookie("sty le");

    if (backlink == ('medium' || 'large' || 'huge')) {

    document.write( " ... ");

    }



    It works if 'backlink' equals medium, but doesn't work on the others.
    What am I missing?



    -- Richard




  • Lasse Reichstein Nielsen

    #2
    Re: simple code not working

    "Richard Barnet" <rbarnet@csaNOS PAMreno.org> writes:
    [color=blue]
    > "Richard Barnet" <rbarnet@csaNOS PAMreno.org> wrote in message
    > news:bguat6$ofj $1@nnrp.atgi.ne t...[color=green]
    > > Why doesn't this work?:
    > >
    > > var backlink = readCookie("sty le");
    > > if (backlink == ('medium' || 'large' || 'huge')) {
    > > document.write( " ... ");
    > > }
    > >
    > > It works if 'backlink' equals medium, but doesn't work on the others.
    > > What am I missing?[/color][/color]

    The expression
    ('medium' || 'large' || 'huge')
    uses short-circuit "or" operators.

    Let's ignore the last "|| 'huge'" part for now, and just look at
    "'medium' || 'large'".

    An "or"-expression is true if either operand is true. The short-circuit
    implementation of an "or"-expression checks the first operand first, and
    if that is true, it never evaluates the second.

    Since the first operand ('medium') is true when converted to a
    boolean, the entire "or" expression is true, and it even evalutates to
    'medium'.

    Add "|| 'huge'", and it still evaluates to 'medium'.

    That is why the comparison is true if "backlink" is the string "medium",
    because it is compares to an expression that evaluates to "medium".
    [color=blue]
    > If I lose the second set of quotes:[/color]

    Parentheses, not quotes. Quotes would be ' and ".
    [color=blue]
    > if (backlink == 'medium' || 'large' || 'huge') { document.write( " ...
    > "); }
    >
    > then it executes the code no matter what backlink equals (i.e., if
    > backlink == 'small', it still writes the code).[/color]

    Because you now have (if I add parentheses to show grouping):
    (backlink == 'medium') || 'large' ...
    If "backlink" is "medium", this gives true (or'ed with something else,
    which is still true).
    If "backlink" is not "medium", it gives false or'ed with 'large',
    which gives 'large', which is also true when converted to a boolean
    (as any non-empty string).

    You need to compare to each possibility in turn:

    if (backlink == 'medium' || backlink == 'large' || backlink == 'huge')...

    /L
    --
    Lasse Reichstein Nielsen - lrn@hotpop.com
    Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit. html>
    'Faith without judgement merely degrades the spirit divine.'

    Comment

    Working...