Bas Joosten

Navigation

Skip navigation.

Search

Site navigation

Email conversation

FromBas Joosten
ToMe
SubjectMistake on the page http://www.howtocreate.co.uk/xor.html
Date30 December 2009 11:57
Hi Tarquin,

on you site howtocreate, on the page 'xor.html', you have written the
following:

Or using the ternary operator to make it even smaller:
if( foo ? !bar : bar ) {
  ...
}
This has a problem that if foo or bar are expressions, and not objects or
literals, they will be evaluated twice.

This is wrong: using (foo? !bar:bar) will cause both foo and bar to be
evaluated only once.
In addition, the function you suggest as a solution:
if( (function (a,b) { return ( a || b ) && !( a && b ); })( foo, bar ) ) {
  ...
}
can cause the parameters to be evaluated twice if they are objects (which
will evaluate to True) since they are passed by reference.

Hope this helps! Yours,

Bas Joosten

PS: your page was very helpful to me, especially the suggestion to use
!foo != !bar or foo ? !bar : bar
FromMe
ToBas Joosten
SubjectRe: Mistake on the page http://www.howtocreate.co.uk/xor.html
Date10 January 2010 20:08
Bas,

> This is wrong: using (foo? !bar:bar) will cause both foo and bar to be
> evaluated only once.

Yep, thanks for the note. I have clarified this in the article.

> In addition, the function you suggest as a solution:
> can cause the parameters to be evaluated twice if they are objects

In these cases, objects are not evaluated as an expression. They are cast
using the internal ToBoolean operator, which returns true for objects. The
overhead is negligible. With expressions, however, it can make a difference
in both execution time and unforeseen side effects, which the solution
avoids.

(If an implicit cast is done to a number or string, then it can invoke the
valueOf and toString methods, which *do* get evaluated as expressons, but
this is not the case for implicit casts to boolean values, for which there
is no overriding method.)

Of course, the ternary operator or !a!=!b approaches are preferred for
clarity and simplicity, as well as avoiding the double evaluation problem.

Thanks again for the note.

Mark 'Tarquin' Wilton-Jones - author of http://www.howtocreate.co.uk/
This site was created by Mark "Tarquin" Wilton-Jones.
Don't click this link unless you want to be banned from our site.