0

Using ternary operator requires two calls to the function.

var colour = (tryAdventurousColour() != null) ? tryAdventurousColour() : 'black';

Possible to do it in 1 line?

EDIT: Fixed syntax EDIT: Like this but better

var colour = ( (colour = tryAdventurousColour() ) != null ) ? colour : 'black';

1
  • 2
    That is incorrect syntax for a ternary expression. Commented Sep 23, 2011 at 3:34

2 Answers 2

5

Use JavaScript's logical or operator:

var colour = tryAdventurousColour() || 'black';

Your function tryAdventurousColour() will be executed once. If it returns a "truthy" value then that colour variable will be assigned to that value, otherwise colour will be 'black'. This fits your scenario perfectly since null is a "falsy" value.

In more general terms, the expression a || b returns a if it can be converted to true (is "truthy"), otherwise it returns b. Note that non-zero numbers, non-empty strings and objects will all be converted to true. null, undefined, 0, "" will all be converted to false. (I'm sure somebody will correct me if I've left something out.)

Sign up to request clarification or add additional context in comments.

5 Comments

Keep in mind that tryAdventurousColour() shouldn't return 0 as a valid color.
Ha! of course: and var colour = (tryAdventurousColour() != failValue) || 'black';
No, don't do var colour = (tryAdventurousColour() != failValue) || 'black' because that will return either true or 'black'. The != expression evaluates to true or false, not to a colour. @katspaugh - good point, but then 0 would be black anyway wouldn't it? Another option is to move the default processing into the function...
@nnnnnn Ah whoops I meant colour = (colour =(tryAdventurousColour() != failValue)) || 'black' but thats just crazy.
Nope, that has the same problem because the expression in the innermost parentheses returns a boolean. colour still ends up as true or 'black'.
-1
 var colour = (tryAdventurousColour()) ? tryAdventurousColour() : 'black';

1 Comment

hhehe ok roger that. If no-one can beat that in a few horus I guess you'll get the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.