simple code not working

R

Richard Barnet

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
 
L

Lasse Reichstein Nielsen

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".
If I lose the second set of quotes:

Parentheses, not quotes. Quotes would be ' and ".
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).

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
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top