simple code not working

Discussion in 'Javascript' started by Richard Barnet, Aug 7, 2003.

  1. Why doesn't this work?:



    var backlink = readCookie("style");

    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
     
    Richard Barnet, Aug 7, 2003
    #1
    1. Advertisements

  2. 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".
    Parentheses, not quotes. Quotes would be ' and ".
    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, Aug 7, 2003
    #2
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.