On Jul 30, 3:26 pm, "T.J. Crowder" <t...@crowdersoftware.com> wrote:
> Hi Alex,
>
> > However it cannot be achieved so it must be done usung if/else..
>
> Well, this is JavaScript, there's almost always a way.  I can think of
> four off the top of my head that keep it in a single expression -- but
> all of them are much worse (most of them much, much, much worse) than
> using an if/else. ;-)  The four are:
>
> 1. Massage the return value of the first thing you want to do to force
> it to be the return value you want.  Actually, in your specific case,
> you don't have to anything:
>
> return $(arg) ? true : alert('Element Does not exist');
>
> alert has no return value, hence your function returns either true or
> undefined, which is good enough for anything branching on its return
> value (undefined is falsey, after all).  If you really want a false,
> use !! to force it.
>
> Blech.
>
> 2. If you wanted to return something other than false, and if the
> first part has an invariant result, you could manipulate that return
> value to be falsey and use the OR operator, which is much more
> powerful in JavaScript than in most languages (more here[1]):
>
> return $(arg) ? "It's there" : (alert('Element Does not exist') ||
> "It's not there");
>
> or, demonstrating manipulation:
>
> return $(arg) ? "It's there" : (!setTimeout(...) || "It's not there");
>
> ...since setTimeout returns a non-zero number; !setTimeout is false
> and so the return value (for that second operand) is "It's not there".
>
> Blech blech.
>
> 3. Wrap the two-part bit in an on-the-fly function:
>
> return $(arg) ? true : (function(){ alert('Element Does not exist');
> return false;})());
>
> Blech blech cough.
>
> 4. Use eval (!):
>
> return $(arg) ? true : eval("alert('Element Does not exist'); return
> false;");
>
> Blech blech cough retch.
>
> I bet there are others.

You can use comma operator (which evaluates all of its expressions
left to right and evaluates itself to the last expression):

return $(arg) ? true : alert('...'), false;

[...]

--
kangax
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Prototype & script.aculo.us" group.
To post to this group, send email to prototype-scriptaculous@googlegroups.com
To unsubscribe from this group, send email to 
prototype-scriptaculous+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/prototype-scriptaculous?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to